I create a date like this:
var date = new Date('Wed, 19 Mar 2014 18:17:00 +0200');
This resolves to:
Wed Mar 19 2014 17:17:00 GMT+0100 (Central European Standard Time)
Is there a way to retrieve the "+0200" portion from the date object once it is created? I am trying to get this without parsing the input string and without the use of external libraries.
EDIT:
When I use
date.getTimezoneOffset();
It returns "-60", which corresponds to the local timezone offset, which in my case is GMT+0100. The question I am asking is whether the "+0200" from the input is lost in the Date object upon creation, or is it stored somewhere?
You can retrieve the timezoneoffset with date.getTimezoneOffset(); and use that to calculate it
From the Mozilla MSDN
The getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.
date.getTimezoneOffset()
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight saving time prevents this value from being a constant even for a given locale.
A date object is stored as the number of milliseconds since the Unix epoch. So your input string is parsed and stored as a primitive number. So no, you can't retrieve aspects of your original input after it has been converted to a date object.
Related
I'm noticing the following weird behaviour for the toTimeString method.
const date1 = new Date("2022-09-23T00:00:00.00Z")
const date2 = new Date()
date1.toTimeString()
//17:00:00 GMT-0700 (Pacific Daylight Saving Time)
date2.toTimeString()
// 15:06:43 GMT-0800 (Pacific Standard Time)
I've also noticed that result for date1 even depends on the device region settings (for Mac at least)
date1.toTimeString()
// if region is set to Canada
// 17:00:00 GMT-0700 (Pacific Daylight Saving Time)
// if region is set to United States
// 17:00:00 GMT-0700 (Pacific Daylight Time)
Another observation
date2.toTimeString()
// this is the result for both United States and Canada
// 15:06:43 GMT-0800 (Pacific Standard Time)
A couple of questions
Why does the result depend on how the date is constructed?
(new Date("2022-09-23T00:00:00.00Z") vs new Date)
For new Date("2022-09-23T00:00:00.00Z"), why does the result depend on the device setting?
The result seems consistent when no arguments are passed e.g new Date(). Can we assume that this will produce a consistent timezone name regardless of device settings?
Note: I also noticed a same behaviour with date-fns-tz
EDIT: added one more example above.
Another question:
4.In contrary to question 2, new Date().toTimeString() is not influenced by region setting. Why is that the case
EDIT 2: I figured it out.
For countries with day light savings. The behaviour of toTimeString() will produce different timezone based on when the timestamp falls in.
Leaving this thread here since it might be helpful to others
First case you call the Date constructor with string representation of the date 2022-09-23 with the time 00:00:00 (GMT offset 0) and it returns the Date object instance for the 09/23/2022 00:00:00. Second case you call empty Date constructor which returns the Date object instance with current date and time.
Next, when you call the toTimeString() method it returns the time portion of a Date object interpreted in the local timezone (see more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString).
If you would like to get the local time zone name better see here How can I get the timezone name in JavaScript?
Why does the result depend on how the date is constructed? (new Date("2022-09-23T00:00:00.00Z") vs new Date)
The timestamp "2022-09-23T00:00:00.00Z" is parsed with zero offset due to the trailing "Z". That effectively makes it UTC.
Calling new Date() creates a Date instance for the current date and time. toTimeString returns the time that a Date instance represents based on system settings. So for a given instance, if you change the location in system settings to a place with a different offset, you'll get a different time.
If regional settings are for a place that observes daylight saving time (DST), then you'll also get a different offset (and civil timezone name) for dates at times of the year when DST is and isn't in effect.
For new Date("2022-09-23T00:00:00.00Z"), why does the result depend on the device setting?
The Date instance created is exactly the same regardless of system settings because the offset is fixed as 0 in the timestamp. The result of toTimeString depends on system settings because that's were it gets its information for the host offset and civil timezone name from.
The result seems consistent when no arguments are passed e.g new Date(). Can we assume that this will produce a consistent timezone name regardless of device settings?
No. Timezone names are not standardised and are implementation dependent per ECMA-262. However, the actual offset should be consistent.
I suggest reading Why does Date.parse give incorrect results? for some background.
new Date("0001-01-01T01:00:00Z") --> Mon Jan 01 0001 02:50:16 GMT+0150 (Moscow Standard Time)
Incorrect GMT: my timezone GMT+3000, but date creates GMT+0150
For dates, you can (and should, in my opinion) define them in UTC ISO 8601 "Z" format ("YYYY-MM-DDTHH:MM:SSZ"), just as you did.
However, to get a user-friendly string representation of those dates, it will depend on your client and on the Javascript engine used. You can constrain the output if you explicitly specify a reference timezone with toLocaleString().
var date = new Date("1990-01-01T01:00:00Z");
console.log(date.toLocaleString("en-US", {timeZone: "Asia/Jerusalem"}));
console.log(date.toLocaleString("en-US", {timeZone: "Europe/Moscow"}));
console.log(date.toLocaleString("en-US", {timeZone: "Africa/Djibouti"}));
// output on my machine, should be the same on yours :
// 1/1/1990, 3:00:00 AM
// 1/1/1990, 4:00:00 AM
// 1/1/1990, 4:00:00 AM
console.log(date.toString());
// output **on my machine**, should **not** be the same on yours
// Mon Jan 01 1990 02:00:00 GMT+0100 (Central European Standard Time)
For the 16 seconds issue, this is linked to the way offset are defined by the rules for those dates before the notion of IANA timezone existed.
They probably don't make sense in your application, and I discourage you to use dates like 1st January of year 0001 for your examples.
Examples :
var date = new Date("0001-01-01T01:00:00Z");
console.log(date.toLocaleString("en-US", {timeZone: "Asia/Jerusalem"}));
console.log(date.toLocaleString("en-US", {timeZone: "Europe/Moscow"}));
console.log(date.toLocaleString("en-US", {timeZone: "Africa/Djibouti"}));
// output on my machine, should be the same on yours :
// 1/1/1, 3:20:54 AM
// 1/1/1, 3:30:17 AM
// 1/1/1, 3:27:16 AM
console.log(date.toString());
// output **on my machine**, should **not** be the same on yours
// Mon Jan 01 0001 01:09:21 GMT+0009 (Central European Standard Time)
More information here (thanks Johan Karlsson for the link) :
https://bugs.chromium.org/p/chromium/issues/detail?id=849404
The most relevant comment from this link is, I think :
This is working as intended and working per spec. The spec says that
we have to follow the IANA timezone database.
In 1880, there's no standard timezone and America/Los_Angeles timezone
offset was based on its longitude. The same is true of other
timezones.
Also note that there are many timezone around the world the zone
offset (and whether or not to have DST or when to start DST) have
changed multiple times even since 2000 (e.g. Europe/Moscow). The
change to make them work correctly also brought in what's reported
here.
Pac0's answer is correct (and you should accept that answer since it came first, not this one). But just to provide a detailed explanation:
Dates from before recorded history of time zones are marked in the time zone database as LMT - which stands for Local Mean Time. The offsets are derived from the latitude and longitude of the city, not by any current political determination.
Since the offset shown is 1:50:16 ahead of UTC, I can derive that your system time zone is Europe/Minsk. This is seen in the tzdb sources here:
# Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Europe/Minsk 1:50:16 - LMT 1880
This is just the first line of the zone entry for Europe/Minsk, which says that until 1880, use the LMT entry of UTC+1:50:16.
As to why it says "Moscow Standard Time" - that string comes from the Unicode CLDR data, which in the /common/supplemental/metaZones.xml file we can see:
<timezone type="Europe/Minsk">
<usesMetazone to="1991-03-30 23:00" mzone="Moscow"/>
<usesMetazone to="2011-03-27 00:00" from="1991-03-30 23:00" mzone="Europe_Eastern"/>
<usesMetazone to="2014-10-26 22:00" from="2011-03-27 00:00" mzone="Europe_Further_Eastern"/>
<usesMetazone from="2014-10-26 22:00" mzone="Moscow"/>
</timezone>
So Europe/Minsk uses the Moscow metazone up until 1991. Then, using one of the language files such as /common/main/en.xml for English, we can see the actual text assigned to this metazone:
<metazone type="Moscow">
<long>
<generic>Moscow Time</generic>
<standard>Moscow Standard Time</standard>
<daylight>Moscow Summer Time</daylight>
</long>
</metazone>
And now you have a complete picture for how the string Mon Jan 01 0001 02:50:16 GMT+0150 (Moscow Standard Time) was derived from 0001-01-01T01:00:00Z.
A timezone is an offset plus a date range. To format your date, javascript wants to know what the timezone offset was for Moscow in the year zero. This is hard information to come by, and might not be accurate ! You think you're asking something simple, but it's actually pretty extreme. If you want to use the date object to represent durations, you should take the epoch as your starting point.
I've got a UTC date through an Ajax call, e.g. "/Date(1517216466000+0100)/",
which is when printing to the console: Mon Jan 29 2018 10:01:06 GMT+0100 (W. Europe Standard Time).
What I need to do, is to let the user change the timezones: I can easily do it with e.g. moment(myDate).tz("Japan").
Then I need to save the date in it's UTC format, which I am not able to do.
I've been experimenting with moment.utc(), but for the input above, it returns 1 hour less.
How to deal with this situation? In summary:
1. Get a UTC time from a webservice
2. Let the user change the timezones
3. Save the modified date in UTC (without the timezone)
Working demo: https://stackblitz.com/edit/angular-kqrct7?file=app%2Fapp.component.html
EDIT for clarification:
Let's just have a look at the hours. What I get the date from the WCF, is 10 o'clock. The browser interprets it as 10 o'clock BUT in GMT+1 so when I convert it to UTC, it becomes 9 o'clock.
I want it to be 10 o'clock as UTC. Then, if I modify the timezone and e.g. the minutes of this date, I want to be able to get the UTC value of this date.
EDIT2: Made my question simplier for clarification
I've got a UTC date, which I get from a webservice like: "/Date(1517216466000+0100)/" which is: Mon Jan 29 2018 10:01:06 GMT+0100 (W. Europe Standard Time) when printed to console.
I add a timezone to it with moment(this.inputDate).tz("Europe/Berlin").format(), but it stays 10:01:06, I guess because of my browsers GMT+1.
I want the ORIGINAL string to be used as a UTC date AND it should remain 10:01:06, not 09:01:06 as you can see above (2nd moment example), so with the timezone "Europe/Berlin" would be 11:01:6
In the .NET JSON formatted date "/Date(1517216466000+0100)/" the timezone offset can be ignored. It represents "2018-01-29T09:01:06.000Z", where the source system was at a timezone offset of +0100. So if you don't care about the source timezone, just ignore it.
It is also an identical moment in time to Mon Jan 29 2018 10:01:06 GMT+0100 (W. Europe Standard Time), just with a different offset.
UTC is not a format, it's a time standard. If you want to use ISO 8601 format:
Extract the first numeric value
Convert to Number
Pass to the Date constructor
Call the toISOString method on the resulting Date
var s = '/Date(-1517216466000+0100)/';
console.log(new Date(+s.replace(/^[^\d-]+(-?\d+).*$/,'$1')).toISOString());
You can also parse and format it using moment.js, which according to the documentation can handle the .NET JSON format without needing to specify the format. So you can either do that or extract the time value and parse it with the "x" format token:
var s = '/Date(1517216466000+0100)/';
// Let moment.js guess the format
console.log(moment(s).utc());
// Extract time value and supply format
console.log(moment(s.replace(/^[^\d-]+(-?\d+).*$/,'$1'), 'x').utc());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
"/Date(1517216466000+0100)/" is a non-standard way to serialise a date/time. Take a look at ISO8601 which defines several standard ways to represent dates and times.
That being said let's take a look at what this gets evaluated as...
moment("/Date(1517216466000+0100)/").toDate()
gives Mon Jan 29 2018 09:01:06 GMT+0000 (GMT Standard Time) for me (in the UK)
taking just the timestamp value 1517216466000
new Date(1517216466000)
also gives Mon Jan 29 2018 09:01:06 GMT+0000 (GMT Standard Time)
this means that the +0100 is being ignored.
You're not actually modifying the time so why would you expect it to save back as anything other than Mon Jan 29 2018 09:01:06
UPDATE
But the "original" string represents Mon Jan 29 2018 09:01:06 UTC the +0100 is ignored and it's just coincidence that your offset to UTC is also +0100. An off.
Offset and timezone are 2 different things. A timezone encompasses offset to UTC as well as when/if daylight savings comes in to force. Just because it says +0100 doesn't necessarily mean (W. Europe Standard Time) as it could just as easily be (West Africa Time) which is also UTC+0100 but doesn't observe daylight savings at all.
The time you have "/Date(1517216466000+0100)/" doesn't convey enough information to say which timezone it is and JS/moment just uses the timestamp 1517216466000 and as such uses UTC. When you console.log() this the browser writes it to screen as local time Mon Jan 29 2018 10:01:06 GMT+0100 (W. Europe Standard Time) but this is only a representation of the underlying datetime.
By telling moment to use a specific time zone, it's only changing how the date/time gets displayed and doesn't actually change the time it represents.
If you use a date picker to change the date/time then you'll have to serialise the value to send to the backend in an appropriate way that the .Net app you cannot change will understand and conveys what you intend.
Example
Get date from server as var serverTime = "/Date(1517216466000+0100)/"
convert this to a JS Date using moment var time = new moment(serverTime)
Let user specify TimeZone i.e. Japan Standard Time (UTC+9) time = time.tz("Japan")
time still represents Mon Jan 29 2018 09:01:06 UTC but when displayed on screen with time.format() gives "2018-01-29T18:01:06+09:00"
You stated "I want it to be 10 o'clock as UTC". Unfortunately the value you've is NOT 10 O'clock UTC and will never be 10 O'clock UTC because it isn't. It is 9 O'clock UTC
You could parse the value you get from the server yourself but the time from the server IS 9am UTC. If you change it to 10 am UTC then you would see that as Mon Jan 29 2018 11:01:06 GMT+0100 (W. Europe Standard Time) - 11 O'clock local time.
Thanks everyone for your detailed answers, they helped me a lot in understanding my problem! However, the right solution was the following:
10 o'clock was a UTC time in the database and it got interpreted as 9 o'clock UTC in Moment.js because C# handled it as a local time. So, before sending the date to the client, I had to indicate that its a UTC:
var utcToClient = DateTime.SpecifyKind(downtime.DownTimeStartUTC, DateTimeKind.Utc)
Then, in Moment I could create a UTC with:
var jsUtc = moment.utc(downtime.DownTimeStartUTC)
Changing the timezones was a breeze with:
jsUtc.tz(userSelectedTimezone)
And saving the date in the database, I used this in C#:
var utcFromClient = Record.DownTimeStartUTC.ToUniversalTime()
I'm trying to pass both date strings to new Date(t).
I expect both strings represent the same time, after all, if I omit the time, shouldn't it be midnight of that day?
But while,
new Date("2016-02-16 00:00")
returns 2016-02-16, midnight, local time as expected,
new Date("2016-02-16")
returns 2016-02-16, midnight UTC, which is wrong, or at least not what I expected given what the other string parses as.
I would understand it if they would both have the same behavior, whether it is to return the time as local time, or as UTC, but it seems very inconsistent why they return different things like this.
As a workaround, whenever I encounter a date that has no corresponding timestamp I can append " 00:00" to get consistent behavior, but it seems like this is rather fragile.
I am getting this value from an INPUT element, of type 'datetime-local' so it seems especially inconsistent that I have to work around a value returned by a page element.
Am I doing something wrong, or should I be doing something differently?
It's what the ES5.1 specification says to do:
The value of an absent time zone offset is “Z”.
It also says:
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
Since the format requires a T separator between date and time, the valid times go to UTC:
> new Date("2016-02-16T00:00:00")
Tue Feb 16 2016 01:00:00 GMT+0100 (CET)
> new Date("2016-02-16")
Tue Feb 16 2016 01:00:00 GMT+0100 (CET)
...while in node.js, an invalid time (without the T separator) seems to go to the implementation specific localtime:
> new Date("2016-02-16 00:00:00")
Tue Feb 16 2016 00:00:00 GMT+0100 (CET)
Note that ES6 changed this, in the same part of the documentation it changes to:
If the time zone offset is absent, the date-time is interpreted as a local time.
The joy of breaking changes.
Edit
According to TC39, the specification is meant to be interpreted as date and time strings without a time zone (e.g. "2016-02-16T00:00:00") are treated as local (per ISO 8601), but date only strings (e.g. "2016-02-16") as UTC (which is inconsistent with ISO 8601).
According to the specifications:
The function first attempts to parse the format of the String
according to the rules called out in Date Time String Format
(15.9.1.15). If the String does not conform to that format the
function may fall back to any implementation-specific heuristics or
implementation-specific date formats.
And Date Time String Formats accept 2016-02-16 as a valid date
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
[...] If the HH, mm, or ss fields are absent “00” is used as the value
and the value of an absent sss field is “000”. The value of an absent
time zone offset is “Z”.
Thus 2016-02-16 translates to 2016-02-16T00:00:00.000Z.
The other date 2016-02-16 00:00 does not conform to the format and therefore its parsing is implementation specific. Apparently, such dates are treated as having local time zone and your example date will return different values depending on time zone:
/* tz = +05:00 */ new Date("2016-02-16 00:00").toISOString() // 2016-02-15T19:00:00.000Z
/* tz = -08:00 */ new Date("2016-02-16 00:00").toISOString() // 2016-02-16T08:00:00.000Z
Summary:
For conforming date time formats the behavior is well defined — in the absence of time zone offset the date string is treated as UTC (ES5) or local (ES6).
For non-conforming date time formats the behavior is implementation specific — in the absence of time zone offset the usual behavior is to treat the date as local.
As a matter of fact, the implementation could choose to return NaN instead of trying to parse non-conforming dates. Just test your code in Internet Explorer 11 ;)
You are perhaps running into a differences between ES5, ES6 implementations and your expected result. Per Date.parse at MDN, "especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone" is significant.
Additional testing in Firefox 44 and IE 11 revealed they both return a date object for new Date("2016-02-16 00:00"), which object returns NaN when atttempting to get a date component value, and whose toString value is
"Invalid Date" (not "NaN"). Hence appending " 00:00 to get consistent behavior" can easily break in different browsers.
As noted in other answers new Date("2016-02-16") uses a timezone offset of zero by default, producing midnight UTC instead of local.
Per DateParser::Parse() of V8 source codes for Chrome.
ES5 ISO 8601 dates:
[('-'|'+')yy]yyyy[-MM[-DD]][THH:mm[:ss[.sss]][Z|(+|-)hh:mm]]
An unsigned number followed by ':' is a time value, and is added to the TimeComposer.
timezone defaults to Z if missing
> new Date("2016-02-16 00:00")
Tue Feb 16 2016 00:00:00 GMT+0800 (China Standard Time)
A string that matches both formats (e.g. 1970-01-01) will be parsed as an ES5 date-time string - which means it will default to UTC time-zone. That's unavoidable if following the ES5 specification.
> new Date("2016-02-16")
Tue Feb 16 2016 08:00:00 GMT+0800 (China Standard Time)
returns 2016-02-16, midnight UTC, which is wrong, or at least not what I expected given what the other string parses as.
It adds the timezone offset to the 00:00
new Date("2016-02-16") outputs Tue Feb 16 2016 05:30:00 GMT+0530 (India Standard Time)
My timezone being IST with an offset value (in minutes) +330, so it added 330 minutes to 00:00.
As per ecma-262, section 20.3.3.2 Date.parse ( string )
If ToString results in an abrupt completion the Completion Record is
immediately returned. Otherwise, parse interprets the resulting String
as a date and time; it returns a Number, the UTC time value
corresponding to the date and time. The String may be interpreted as a
local time, a UTC time, or a time in some other time zone, depending
on the contents of the String.
When you explicitly set the time-units new Date("2016-02-16 00:00") it wll use set that as hours and minutes,
Otherwise as stated here in 20.3.1.16
If the time zone offset is absent, the date-time is interpreted as a
local time.
I have a scenario where I am using AngularJS to read date. Interestingly it decreases my date value by one.
Why is this happening?
new Date("2016-01-06T00:00:00")
give me result as
Tue Jan 05 2016 16:00:00 GMT-0800 (Pacific Standard Time)
This is because when you use the new Date() in the JavaScript, it converts and prints the date in browsers timezone.
So if you print:
new Date("2016-01-06T00:00:00-0800")
You will get the actual output you want, because of the -0800 difference between your time zone (determined by the browser) and the UTC time.
The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information (note that ECMAScript 2015 specifies that date time strings without a time zone are to be treated as local, not UTC).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Since your date string appears to lack one, JS assumed it's UTC time. The result you see is the same moment in time, offset to your timezone. All you need to do is provide timezone data to the string you're parsing.
It is because the date is taking your browser's timezone in to account, which in your case is in PST. It does the same to me, in EST:
test = new Date("2016-01-06T00:00:00")
Tue Jan 05 2016 19:00:00 GMT-0500 (EST)
You can still obtain the time in UTC by using any of the .getUTC* functions, like so:
test.getUTCDate();
6