1

How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.

new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"

and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?

Kitty
  • 157
  • 5
  • 14
  • If you have option why not use momentjs https://momentjs.com/ – Gary Jun 07 '17 at 15:50
  • I want to do it using plain javascript – Kitty Jun 07 '17 at 15:51
  • 1
    Others here are giving advice that may or may not be applicable to the exact problem you have, because you didn't define your question well. Please give an exact example of what you expected for the output. Also, recognize that UTC is not a "format". I think you mean ISO-8601 format? – Matt Johnson-Pint Jun 07 '17 at 16:28
  • 1
    [*toISOString*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toutcstring) is defined as always returning UTC, so it will always use offset +00:00 (i.e. Z). The host timezone offset for any date is returned in minutes by *getTimezoneOffset*, but note that the sign is opposite to that used by ISO 8601 so -04:00 is +240. and +05:30 is -330. – RobG Jun 07 '17 at 20:54
  • `var isoDate = new Date('date').toISOString();` or `var d = new Date(); var n = d.toUTCString();` If you specify how you want the date to be shown it will be definitely helpful for the question. https://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc – Gary Jun 08 '17 at 02:56

3 Answers3

3

If you want the time to default to midnight in UTC, you can use Date.UTC(year, month, ...) to first create a timestamp based in UTC.

var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)

Then, create the Date from that timestamp.

new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"

However, if you're wanting to know the timezone stored in the Date object, it doesn't actually have that. Dates represent an "instant" in time as the total number of milliseconds that have passed since Jan 1, 1970 00:00:00.000 UTC.

new Date().getTime(); // 1496851...

A Date can tell you the user's local offset from UTC in minutes at that instant.

new Date().getTimezoneOffset(); // e.g. 0, -480, 300

Otherwise, the timezone is limited to two choices when creating date strings, and the choice is based on the method used – user's local timezone or UTC.

new Date().toString();    // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.
RobG
  • 142,382
  • 31
  • 172
  • 209
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
2

You're confused ISO date values do not show the "time zone" instead they show the UTC time. Z stand for Zulu (UTC time).

2017-06-07T15:29:23.692Z

The bold part is not the time zone. It is the milli-seconds, the full time is in UTC. The reason it shows a 000Z in the set Date is because you didnt' set the milli-seconds.

If you want to display the time zone use toUTCString(). However it will display GMT which is UTC/Greenwich Time. To display the local time zone in a the date format you can use date.toLocaleString('en-US',{timeZoneName:'short'}) for example will display the date plus the local US time zone. Or you can use toString() which will display the GMT offset + the long local time zone.

Canolyb1
  • 672
  • 5
  • 17
0

In javascript, parsing, rendering and constructing dates will always assume local. It will convert to a timestamp, the number of milliseconds since 1-1-1970 00:00:00. JSON.stringify will convert to a UTC string, but legacy framworks use local dates. Always beware of this.

var myDate = new Date(); // this is now.

you can get your timezoneoffset (in minutes) with myDate.getTimezoneOffset(), but this will return the same offset for every date (aside from daylight saving time)

You shouldn't do this:

var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon

Date has a few methods to format dates, but always as local or UTC date. You need to do it manually if you want different time zones.

Note: the Date.UTC(...) function returns a timestamp. You sometimes see shifted dates, so they behave like UTC. But this causes problems later on.

var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)

BTW Edge, Chrome and Firefox display dates differently in the console: Edge and Firefox always shows local date, Chrome shows UTC. Also, if you change your timezone, Edge will screw up.

realbart
  • 3,497
  • 1
  • 25
  • 37
  • 1
    Actually, the `Date` object itself just keeps a timestamp that is UTC based. It applies the local time zone when you call one of the functions (either explicitly or implicitly) that uses local time. – Matt Johnson-Pint Jun 07 '17 at 16:22
  • Regarding the approach of subtracting the offset, the term for that when done properly is called "epoch shifting" - because you are adjusting the epoch on which the timestamp is based. The *only* time this is appropriate is if you are working purely with UTC functions, such as `.getUTCFullYear()`, etc. If one shifts the way you showed and then calls `.getFullYear()`, or `.toString()`, or any other local-time function - then the original epoch is assumed, and the local time zone transitions can interfere. Basically, you picked a different point in time, rather than adjusting for time zone. – Matt Johnson-Pint Jun 07 '17 at 16:25
  • @MattJohnson: actually, it doesn't. Try this: assign var d = new Date(). then check the value: alert(d). Then change your local timezone. And do Alert again. I got: Wed Jun 07 2017 18:27:39 GMT+0200 (West-Europa (zomertijd)) and Wed Jun 07 2017 18:27:39 GMT+0200 (Coordinated Universal Time). So the time itself stayed the same, just in a different timezone. – realbart Jun 07 '17 at 16:31
  • Do `d.valueOf()`. That's what is stored internally in a `Date` object. If you just emit a `Date` object (or `Console.log` it), you are seeing a string representation - which may be created by an implicit call to `.toString()` or `.toUTCString()` depending on your browser/environment. The spec doesn't say which one should be used when implicitly converted to a string. If it uses `.toString()`, then during that function you are getting the local time zone applied. – Matt Johnson-Pint Jun 07 '17 at 16:33
  • @Matt: that is my point. Javascript knows **only** local time. So you **cannot** get a UTC Date because they don't exist. However, if you ignore the timezone-part of a date (which it hasn't got anyway) you could use a Date to store the datetime-part of a UTC-date. If you REALLY don't want to use nodatime. – realbart Jun 07 '17 at 16:33
  • BTW - Moment.js uses epoch shifting internally, and you can see another correct example of this technique [in this answer](https://stackoverflow.com/a/32002827/634824). – Matt Johnson-Pint Jun 07 '17 at 16:33
  • 1
    Sorry, I appreciate your enthusiasm, but I feel the need to correct you - as to not perpetuate misinformation. Dates in JS are *always* UTC based. That is, they *only* contain a number of milliseconds since `1970-01-01 00:00:00 UTC`. Local time only kicks in when you call a function that is local-time based. If do `console.log(new Date())`, and your implementation chooses to implicitly do that as `console.log(new Date().toString())`, it's the `toString` call that is reading the computer's local time zone. – Matt Johnson-Pint Jun 07 '17 at 16:36
  • @MattJohnson Thank you, I stand corrected. I learned some new thins today, too. 1. The specs don't say how to internally store a datetime (only the behavior), so different browsers do it differently. 2. The timezone when using the date constructor is different for different ECMAscript version specs. 3. Edge behaves VERY strangely when you change your timezone: you can create a date d for which ''+d != ''+new Date(+d) – realbart Jun 07 '17 at 16:58