javascriptdatedatepickertimezone

Create a Date in js ignoring timezone


Is it possible in js to create a date object that is not affected by timezone? For example i want to set the year "2015", the month "03" and the day "31".

var ex = new Date(2015,3,31);

If i "print" this variable now it appears like this:

Fri May 01 2015 00:00:00 GMT+0200 (ora legale Europa occidentale)

It changes to the next day. Is possible to avoid that? How can i create a Date object that is always the same in every timezone?

I need to include this behavior in an application asap and i cannot work with just Strings because we have to use a datepicker plugin (Bootstrap) which works with date objects.

Thanks in advance


Solution

  • Yes! If you create all your Date objects using the Date.UTC function, then they will all be relative to the standard UTC timezone, even if the user's browser has a different timezone set.

    For example:

    var ex = new Date( Date.UTC( 2015, 3, 31 ) );
    

    This will create a Date object for 3/31/2015 UTC and be consistent across all browsers regardless of their default timezone.

    Internally, the date inside ex will still be converted in the user's local timezone. So if you read values from it, say the date, it will be relative to the user's browser time.

    So if you need to read the time back out in UTC, you can do something like this:

    ex.getUTCYear(); // 2015
    ex.getUTCMonth(); // 3
    ex.getUTCDate(); // 31
    

    This will give you the value back in UTC time.