Create a Date with a set timezone without using a string representation

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date object for my current timezone:

new Date(xiYear, xiMonth, xiDate)

Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.

The problem here is that I then pass this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.

The accepted answer pointed me in the right direction, however just using setUTCHours() by itself changed:

Apr 5th 00:00 GMT+01:00 


Apr 4th 23:00 GMT+01:00

I then also had to set the UTC date, month and year to end up with

Apr 5th 01:00 GMT+01:00

which is what I wanted.

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.

You cannot set it using UTC in the constructor though, unless you specify a date-string.

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

This answer is tailored specifically to the original question, and will not give the answer you necessarily expect. In particular, some people will want to subtract the timezone offset instead of add it. Remember though that the whole point of this solution is to hack javascript’s date object for a particular deserialization, not to be correct in all cases.

I believe you need the createDateAsUTC function (please compare with convertDateToUTC)

function createDateAsUTC(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 

Simply Set the Time Zone and Get Back According

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

Other Time-zones are as Following

var world_timezones =

I don’t believe this is possible – there is no ability to set the timezone on a Date object after it is created.

And in a way this makes sense – conceptually (if perhaps not in implementation); per (emphasis mine):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Once you’ve constructed one it will represent a certain point in “real” time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone – and the constructor you are calling (arguably correctly) translates your “local” time variables into GMT when it stores them canonically – so there is no way to use the int, int, int constructor for GMT times.

On the plus side, it’s trivial to just use the constructor that takes a String instead. You don’t even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror (“Invalid Date”) , Safari (“Invalid Date”) and IE (“NaN”). I suppose you’d just have a lookup array to convert the month to a string, like so:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');

I know this is old but if it helps you could use moment and moment time zone. If you haven’t seen them take a look.

two really handy time manipulation libraries.

If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, …, including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:

// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34"              -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56"           -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78"        -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100"   -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530"   -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330"   -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330"      -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z"          -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
    var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
    var m = timebits.exec(dateString);
    var resultDate;
    if (m) {
        var utcdate = Date.UTC(parseInt(m[1]),
                               parseInt(m[2])-1, // months are zero-offset (!)
                               parseInt(m[4]), parseInt(m[5]), // hh:mm
                               (m[6] && parseInt(m[6]) || 0),  // optional seconds
                               (m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
        // utcdate is milliseconds since the epoch
        if (m[9] && m[10]) {
            var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
            utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
        resultDate = new Date(utcdate);
    } else {
        resultDate = null;
    return resultDate;

That is, you create a ‘UTC time’ using the date without timezone (so you know what locale it’s in, namely the UTC ‘locale’, and it’s not defaulted to the local one), and then manually apply the indicated timezone offset.

Wouldn’t it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes….

d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));

offset value base on which location time zone you would like to set 
For India offset value +5.5,
New York offset value -4,
London offset value +1

for all location offset Wiki List of UTC time offsets

getTimeZoneOffset is minus for UTC + z.

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

This may help someone, put UTC at the end of what you pass in to the new constructor

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

One line solution

new Date(new Date(1422524805305).getTime() - 330*60*1000)

Instead of 1422524805305, use the timestamp in milliseconds
Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)

// My clock 2018-07-25, 00:26:00 (GMT+7)
let date = new Date(); // 2018-07-24:17:26:00 (Look like GMT+0)
const myTimeZone = 7; // my timeZone 
// my timeZone = 7h = 7 * 60 * 60 * 1000 (millisecond);
// 2018-07-24:17:26:00 = x (milliseconds)
// finally, time in milliseconds (GMT+7) = x + myTimezone 
date.setTime( date.getTime() + myTimeZone * 60 * 60 * 1000 );
// date.toISOString() = 2018-07-25, 00:26:00 (GMT+7)

The easiest way that I have found to get the correct date is using datejs.

I get my dates via Ajax in this format as a string: ‘2016-01-12T00:00:00’

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());

Console will read:

Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

The ‘addMinutes’ comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

I thought that this might help someone…

This code will return your Date object formatted with the browser timezone.

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;


To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.

function setTimeZone(date) {
    date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
    return date;

any mileage in

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

Best Solution I have seen from this came from

Print Time Function

<script language="javascript" type="text/javascript">
//borrowed from echoecho
workDate = new Date()
UTCDate = new Date()

function printTime(offset) {
    tempDate = new Date()
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

Full Code Example


<script language="javascript" type="text/javascript">
//borrowed from echoecho
workDate = new Date()
UTCDate = new Date()

function printTime(offset) {
tempDate = new Date()
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)


Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<script language="JavaScript">document.write(printTime("-5"))</script>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>


GMT -03:00 Example

new Date(new Date()-3600*1000*3).toISOString();  // 2020-02-27T15:03:26.261Z

Or even

now  = new Date().getTime()-3600*1000*3; // 1582818380528
data = new Date(now).toISOString();      // 2020-02-27T15:03:26.261Z

I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.

Key info:

  1. ISO is the Javascript preferred date standard. Assume date utilities will likely return date values in that format.
    • My date picker displays the date in a localized format: mm/dd/yyyy

    • However, it returns the date value in the ISO format: yyyy-mm-dd

      //Select "08/12/2020" in Date Picker date_input 
      var input = $('#date_input').val();  //input: 2020-08-12
  1. Date.getTimezoneOffset() returns the offset in minutes.


If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.

var input = $('#date_input').val();  //input: 2020-08-12
var date = new Date(input);          //This get interpreted as an ISO date, already in UTC
//date:                             Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'):       8/11/2020

Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.

var date = new Date("08/12/2020");  //This gets interpreted as local timezone
//date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'):       8/12/2020


To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset() with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.

var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'):       8/12/2020

const date = new Date("2020-12-16 17:45:00 UTC");

Works fine.

You can use library to help to change time zone


var moment = require("moment-timezone");
const today = new Date();
var timeGet = moment(today);"Asia/Karachi").format("ha z");

this can change your time zone of your region paste your region area and get real gmt+ resolve issue

For more details visit moment timezone official documentation

This worked fine for different timezones (IST, PST, Mexico, Central America):

let dateUtc: any = new Date(Date.parse(data.details.dateOfBirth));

dateUtc = new Date(dateUtc.getTime() + Math.abs(dateUtc.getTimezoneOffset()*60000));


if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.

  const currTimezone = new Date().getTimezoneOffset(); // your timezone
  const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone

  if (currTimezone !== newDateTimezone) {
    // and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
    const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
    date.setTime(date.getTime() + (newTimezone * 60 * 1000));

When I create a date object:

new Date(year, month, day, hour, minute)

I works fine on localhost.
When I deploy to server it breaks, because server is in another timezone.

I can’t use getTimezoneOffset(). I need the timezoneOffset of my home – dependent on summertime/wintertime

// add diff minutes between myself (HOME) and server 
timezoneHomeOffset (d, tz = 'Europe/Copenhagen') {
  const utc = new Date(d.getTime())
  const dHome = new Date(d.toLocaleString('en-US', { timeZone: tz }))
  const diff = Math.round((utc - dHome) / 60000) // 60*1000 => minutes
  d.setMinutes(d.getMinutes() + diff)
  return d

It’s actually not very hard at all to do this, but it certainly isn’t intuitive to come up with the solution. There are some really convoluted answers here (though also some nice ones). Here’s what I came up with to make sure my server timestamps would match my local timestamps, no matter what timezone my deployed server happened to be in.

(CET = Central European Timezone, which just happens to be my personal timezone; you can get the offset of any given timezone and calculate it and even make it an argument if you like, but for my purpose, I just needed to get my dates to all be the single desired consistent timezone.)

    const convertDateToCET = function(date) {
        date = new Date(date)
        // let startTime = date.getTime();
        const cetOffset = -120; // this is the number you get from running 
        // `(new Date()).getTimezoneOffset()` if you're on a machine in CET
        const offsetFromCET = (date.getTimezoneOffset() - cetOffset);
        const cetMillsecondOffset = ( cetOffset* 60 * 1000);
        date = new Date( date.getTime() - cetMillsecondOffset ) 
        // let endTime = date.getTime()
        // console.log("updated date from",startTime,"to",endTime)
        return date;

Using this, you just make a time the way you would expect, e.g.

    let myDate = new Date("12-4-2021")
    // now myDate is 2:30pm, December 4th, 2021, in whatever the timezone the machine of code running happens to be in
    myDate = convertDateToCET(myDate)
    // now myDate will show up as 2:30pm, Dec 4th, 2021, mapped into your local timezone
    // so, if you're in the UK, and one hour behind CET, myDate is now 1:30pm, Dec 4th, 2021

The key here is date.getTimezoneOffset(). If you’re actually in CET, that number will be -120, and so it cancels out, making no difference (so CET results in CET out). If you’re in the UK, one hour behind CET, that output would be -60, which means -60 + 120 = +60 which results in us changing the input time by one hour, and so on.

It probably makes more sense to convert everything and use everything in UTC for a case like this, but given that all of my input time is in CET and I’d originally developed the system based on how things looked locally on my machine, this utility allowed me to convert the existing code by just making a call to this function in a few key places.

Caution: Make sure not to apply this function call multiple times on the same date, as you’ll be reapplying the offset multiple times, throwing it off!

This worked for me. Not sure if it is a good idea though.

var myDate = new Date();
console.log('myDate:', myDate);   // myDate: "2018-04-04T01:09:38.112Z"

var offset="+5";  // e.g. if the timeZone is -5

var MyDateWithOffset = new Date( myDate.toGMTString() + offset );   

console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"

I used the timezone-js package.

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;


    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());

This is BEST solution


// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC

// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC


Date.prototype.timezoneOffset = new Date().getTimezoneOffset();

Date.setTimezoneOffset = function(timezoneOffset) {
  return this.prototype.timezoneOffset = timezoneOffset;

Date.getTimezoneOffset = function() {
  return this.prototype.timezoneOffset;

Date.prototype.setTimezoneOffset = function(timezoneOffset) {
  return this.timezoneOffset = timezoneOffset;

Date.prototype.getTimezoneOffset = function() {
  return this.timezoneOffset;

Date.prototype.toString = function() {
  var offsetDate, offsetTime;
  offsetTime = this.timezoneOffset * 60 * 1000;
  offsetDate = new Date(this.getTime() - offsetTime);
  return offsetDate.toUTCString();

['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
  return function(key) {
    Date.prototype["get" + key] = function() {
      var offsetDate, offsetTime;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      return offsetDate["getUTC" + key]();
    return Date.prototype["set" + key] = function(value) {
      var offsetDate, offsetTime, time;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      offsetDate["setUTC" + key](value);
      time = offsetDate.getTime() + offsetTime;
      return time;

Coffee version:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset()

Date.setTimezoneOffset = (timezoneOffset)->
    return @prototype.timezoneOffset = timezoneOffset

Date.getTimezoneOffset = ->
    return @prototype.timezoneOffset

Date.prototype.setTimezoneOffset = (timezoneOffset)->
    return @timezoneOffset = timezoneOffset

Date.prototype.getTimezoneOffset = ->
    return @timezoneOffset

Date.prototype.toString = ->
    offsetTime = @timezoneOffset * 60 * 1000
    offsetDate = new Date(@getTime() - offsetTime)
    return offsetDate.toUTCString()

    'Milliseconds', 'Seconds', 'Minutes', 'Hours',
    'Date', 'Month', 'FullYear', 'Year', 'Day'
.forEach (key)=>
    Date.prototype["get#{key}"] = ->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        return offsetDate["getUTC#{key}"]()

    Date.prototype["set#{key}"] = (value)->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        time = offsetDate.getTime() + offsetTime
        return time

Leave a Comment