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()
Related
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.
using date picker I am getting this value "Fri Jan 12 1900 05:21:10 GMT+0521 (India Standard Time)" I want to get it's value in UTC or UTC in milliseconds or long value.
here is my code
app.controller('MainCtrl', function($scope, moment) {
$scope.UTC ='';
$scope.IST = 'Fri Jan 12 1900 05:21:10 GMT+0521 (India Standard Time)';
});
According to the Moment docs:
moment.utc(yourDate).format()
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
While in UTC mode, all display methods will display in UTC time instead of local time.
I use the datepicker to pick a date and send it to the server.
When I log the JS value I get the correct result:
Tue Mar 22 2016 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
but in the ajax request it is
2016-03-21T23:00:00.000Z
I don't modify the values, just giving the object to angulars http function.
Does Angular need some configuration to handle it?
You can try the following piece of code
dateObj.setMinutes((dateObj.getMinutes() + dateObj.getTimezoneOffset()));
No need of localization, use this code just before doing any service call. It will pass you the exact date what you selected in the datepicker.
It will work in all timezone (+) and (-),
Example: 2016-03-21 00:00:00 GMT+0100, the above said code covert it as 2016-03-21 01:00:00 GMT+0000. While on Service it converts it as 2016-03-21 00:00:00.
I think it will solve your problem.
Those two strings represent the same time. One is in UTC, i.e. GMT +0, which you can see from the Z ending. The other is in a different timezone, specifically GMT +1 hour.
If you had javascript date objects for both strings, and turned them into integers, i.e. seconds passed since Jan 1, 1970, UTC, you'd find them identical. They represent the same instant but in two different geographic locations.
var d1 = new Date('Tue Mar 22 2016 00:00:00 GMT+0100');
var d2 = new Date('2016-03-21T23:00:00.000Z');
Number(d1); // 1458601200000
Number(d2); // 1458601200000
Generally this is a good thing. Dealing in timezones gets very confusing. I find it best for a server to always deal in UTC.
https://github.com/angular/material/pull/9410
Check out the 1.1.1+ version. This will solve your issue.
<md-datepicker ng-model="date" ng-model-options="{ timezone: 'utc' }"></md-datepicker>
If suppose am selecting a date like Tue Aug 06 2019 00:00:00 GMT+0530 (India Standard Time), am getting 2019-08-05T18:30:00.000Z. ( which in my case previous date with respect to the selected date)
I made use of toLocalDateString() to do the job.
// this.date = 2019-08-05T18:30:00.000Z
const converted = new Date(this.date).toLocaleDateString();
console.log(converted); // 8/6/2019 (MM/DD/YYYY) format
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
var dt = new Date("2012-04-23T12:00:00");
var dtz = new Date("2012-04-23T12:00:00Z");
If the Z is present I get a different time.
When the Z is present is it converting the Date to the browser's local time and when not present assuming it is already in local time?
I get different results in FF than Chrome. Chrome always gives me the same time. FF treats them as different. How should I be dealing with UTC dates from the server?
"Z" is a military time zone corresponding to UT (aka UTC, aka GMT). So basically, 'nnn Z' means "how late is it in your time zone when it's 'nnn' in Greenwich". For example, I'm in CEST which is GMT+2 so this
new Date("2012-04-23T12:00:00Z")
returns for me:
Mon Apr 23 2012 14:00:00 GMT+0200 (CEST)
As to dates with a TZ specifier, they seem to be treated differently in Firefox (which assumes local TZ) and Chrome (which assumes UTC). For safety, I'd suggest always using an explicit TZ specifier.
var dt = new Date("2012-04-23T12:00:00");
var dtz = new Date("2012-04-23T12:00:00Z");
tried it with alert() and got these messages
alert(dt);
Mon Apr 23 2012 12:00:00 GMT+0500 (West Asia Standard Time)
alert(dtz);
Mon Apr 23 2012 17:00:00 GMT+0500 (West Asia Standard Time)
it means that if you create the date without "Z", it returns browsers's local time at GMT, mentioning your time zone is below or above GMT
and if you create it with "Z", it will show the local time at your time zone, referring to your time zone.
According to ISO 8601, IF no UTC relation information is given with a time representation, the time is assumed to be in local time.
If can verify the correct behavior on both Firefox, Safari and Internet Explorer:
The following should return: false
new Date("2014-05-09T22:12:18.893Z").valueOf() === new Date("2014-05-09T22:12:18.893").valueOf()
If you try the same thing on Chrome or Opera, it will incorrect indicate: true
The moral of the story is, if you have a string in the above format, add a Z at the end.