I have a string "2017-01-05T15:03:25.21" which is already the exact time in my timezone. (eg: +8) How to convert this string into the Date Object? The reason of asking this is that, the Date class seems to accept a 'UTC Date String' only. If i directly do this:
var strDateTime = "2017-01-05T15:03:25.21";
var myDate = new Date(strDateTime);
//myDate will have another redundant time-zone offset.
How to convert this properly?
How to convert this properly?
Implementations consistent with ECMAScript ed 5 (ES5) and later will parse the string correctly with either the Date constructor or Date.parse, so:
var strDateTime = "2017-01-05T15:03:25.21";
var myDate = new Date(strDateTime);
Will produce a date for 5 Jan 2017 3:03:25.21 PM in the local timezone.
However, it's not recommended to do that given the general inconsistencies in parsing between implementations. Either a custom function or library should be used, e.g. using fecha.js:
var myDate = fecha.parse(strDateTime, "YYYY-MM-DDTHH:mm:ss.SS")
From ES5 and later, ISO 8601 date and time strings are mostly parsed as specified in ISO 8601. The main differences are:
So given:
var s = "2017-01-05T15:03:25.21";
var d = new Date(s)
then d will be converted to a Date with a UTC time value based on the host system timezone setting. If your host is set to UTC+0800, then that is the timezone that is applied.
Date objects do not have a time zone. All they have is a single time value that represents milliseconds since 1970-01-01T00:00:00Z. Any related time zone information comes from the host. So the comment:
//myDate will have another redundant time-zone offset.
is incorrect. The host time zone setting will be used to determine the offset that is used to calculate the UTC time value, and also to calculate the local values returned by the get* methods like getFullYear, getMonth, getDate, getHours, etc.
The string "2017-01-05T15:03:25.21" on a system with an offset of +0800 will generate a time value of 1483599805210, which represents 2017-01-05T07:03:25.21Z (i.e. UTC+0000).
If you wish to send a timestamp that represents a particular moment to clients in different time zones, then one of the following should suite.
Append the time zone to the string:
2017-01-05T15:03:25.21+0800
Use the UTC equivalent:
2017-01-05T07:03:25.21Z
Use a time value:
1483599805210
The last is generally preferred as new Date(timevalue)
is supported by all implementations, is unambiguous and can be easily converted for use in other systems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With