简体   繁体   中英

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

The short answer is you can't.

A Date object is just an accessor to the system time settings (so it will use the local computer timezone anyway). You can then manipulate your dates by substracting the local timezone using getTimezoneOffset(), or forcing a time with setUTCHours().

However if you can welcome only one TimeZone accross your applcation, you can get date time at that paticular timezone using moment.js :

 moment().tz("America/Los_Angeles").format(); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM