String to date converter issue in js - javascript

My local machine in EST timezone.
I'm trying to convert date string to date object in js but getting an day before from date string in date object.
new Date('2020-04-03') for this i'm getting Thu Apr 02 2020 20:00:00 GMT-0400 (Eastern Daylight Time) this output.
new Date('2020/04/03') for this i'm getting Fri Apr 03 2020 00:00:00 GMT-0400 (Eastern Daylight Time) this output.
console.log(new Date('2020-04-03'))
console.log(new Date('2020/04/03'))
I don't know what is the difference between these can anyone explain that?
How i fix this issue?

The reason why the two date parsings give you different results is because it's triggering two different date handling modes.
In one case, 2020-04-03, it's treating the date as an simplified version of ISO 8601 format, for which JavaScript creates a date in the UTC time zone if no time zone is specified.
The second date, 2020/04/03, is not in an officially supported format, so JavaScript falls back to an implementation-specific parsing of the date, so it may not even be consistent across browsers. In that case, it's choosing to use your local time zone.
The MDN article on Date.parse() offers a detailed explanation of how date parsing works in the JavaScript standard and how non-standard behaviors exist among browsers in some cases.
In short, it's a good idea to stick with ISO 8601 dates whenever possible, not only because JavaScript handles them in a consistent way, but they're also easily sorted, and they're widely supported across many programming systems.

Try new Date('2020-04-03 00:00:00')

By default, the date string is parsed in UTC timezone. When you output a date, by default it converts it to your local timezone set by your browser.
To solve, you can enter your date as the UTC equivalent, or simply do as the others have stated here and include the timezone in your date string
let date = new Date('2020-04-03 EST');

Related

How to stringify dates with timezones properly in javascript?

In javascript, I have a date in UTC, and I want to stringify it and parse it but maintain it's UTC. I did this code
var f = { f : new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)")}
undefined
JSON.stringify(f)
"{"f":"2019-05-28T00:11:13.000Z"}"
JSON.parse(JSON.stringify(f))
{f: "2019-05-28T00:11:13.000Z"}
You can see that after I stringified it, it changed to the next day. And then when I parse it, it kept it as a string and even of the next day. I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time).
Does anyone know what's wrong?
Thanks
You can see that after I stringified it, it changed to the next day
No, it didn't. "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" was parsed to a time value of 1559002273000, which defines a moment in time that is that many milliseconds after 1970-01-01T00:00:00Z. It's equivalent to 2019-05-28T00:11:13.000Z (and other timestamps in other time zones). E.g. on a system set to an eastern Australian timezone you'd get "Tue May 28 2019 10:11:13 GMT+1000 (AEST)".
I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)
The date object has no knowledge of the timezone of the original timestamp, it just stores the time value. The string produced by toString just uses the host system timezone setting to generate a "local" timestamp in the format specified by ECMA-262. Note that the timezone name is implementation dependent and since they aren't standardised, the names and abbreviations differ between implementations. E.g. Safari shows "AEST" and Firefox "Australian Eastern Standard Time".
You can use toLocaleString to generate timestamps for different timezones, but the date object doesn't know what the original timezone was and the format may not be what you want.
Also, toLocaleString uses IANA timezone identifiers (e.g. Africa/Kinshasa), which relate to geographic locations that are used to deduce the applicable timezone rather than common names like "Eastern Daylight Time" which are not standardised and can be ambiguous or obscure. The IANA designators mean things like daylight saving and historic timezone offset changes can be applied more easily than with other designators.

Safari and Chrome showing different results of new Date() [duplicate]

I want to convert date string to Date by javascript, use this code:
var date = new Date('2013-02-27T17:00:00');
alert(date);
'2013-02-27T17:00:00' is UTC time in JSON object from server.
But the result of above code is different between Firefox and Chrome:
Firefox returns:
Wed Feb 27 2013 17:00:00 GMT+0700 (SE Asia Standard Time)
Chrome returns:
Thu Feb 28 2013 00:00:00 GMT+0700 (SE Asia Standard Time)
It's different 1 day, the correct result I would expect is the result from Chrome.
Demo code: http://jsfiddle.net/xHtqa/2/
How can I fix this problem to get the same result from both?
The correct format for UTC would be 2013-02-27T17:00:00Z (Z is for Zulu Time). Append Z if not present to get correct UTC datetime string.
Yeah, unfortunately the date-parsing algorithms are implementation-dependent. From the specification of Date.parse (which is used by new Date):
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. 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.
To make the Date constructor not (maybe) use the local timezone, use a datetime string with timezone information, e.g. "2013-02-27T17:00:00Z". However, it is hard to find a format that is reliable parsed by every browser - the ISO format is not recognised by IE<8 (see JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse). Better, use a unix timestamp, i.e. milliseconds since unix epoch, or use a regular expression to break the string down in its parts and then feed those into Date.UTC.
I found one thing here. It seems the native Firefox Inspector Console might have a bug:
If I run "new Date()" in the native Inspector, it shows a date with wrong timezone, GMT locale, but running the same command in the Firebug Extension Console, the date shown uses my correct timezone (GMT-3:00).
Noticed that FireFox wasn't returning the same result as Chrome. Looks like the format you use in kendo.toString for date makes a difference.
The last console result is what I needed:
Try using moment.js. It goes very well and in similar fashion with all the browsers. comes with many formatting options. use moment('date').format("") instead of New Date('date')

new Date() with ISO 8061 date creates date according to timezone

If i create Date object with new Date('2015-03-25') , I'm getting object as Tue Mar 24 2015 16:00:00 GMT-0800 (AKDT). Is it expected ?
Is it expected?
Unfortunately Ecma TC39 decided that date only forms of ISO 8601 strings should be treated as UTC and not local (per ISO 8601).
You might care to read Matt Johnson's blog on the issue.
The only reliable way to parse date strings is to do it manually. A library can help, but is usually not necessary.

Convert given UTC string and Timezone offset from JavaSscript to UTC format in SQL Server

I have been assigned a task where I have UTC string and timezone offset created in javascript code and they needs to be saved in sql server datetime column with UTC format.
UTC string is created as (new Date()).toUTCString();
Example: Thu, 03 Mar 2016 06:19:11 GMT and
Timezone is created as new Date().getTimezoneOffset();
Example: -330
Having no experience working with time zones, I am confused.
I think you're looking for Date.prototype.toISOString, which returns an ISO 8601 string in timezone UTC, e.g.
document.write( new Date().toISOString() );
The toUTCString method is implementation dependent, so not consistent across hosts. Also, the ECMAScript timezone offset has the opposite sense to ISO 8601 and those in common use, e.g. for a host set to UTC+5:00, getTimezoneOffset returns -300 (minutes).
If you need a pollyfill for toISOString to accommodate old hosts (e.g. IE 8), see MDN.

Javascript new Date(str) - different parsing rules

I tried this in the Chrome JS console, with my locale time zone set as PST:
(new Date("07-15-2005"))
=> Fri Jul 15 2005 00:00:00 GMT-0700 (PDT)
(new Date("07-15-2005")).getTime();
=> 1121410800000
but....
(new Date("2005-07-15"))
=> Thu Jul 14 2005 17:00:00 GMT-0700 (PDT)
(new Date("2005-07-15")).getTime();
=> 1121385600000
I was expecting string parsing to occur in both. But I can't make out why when format YYYY-MM-DD is used, it assumes a timezone offset. It's as if I'm expressing "2005-07-15" in my local TZ, but "07-15-2005" is expressed in UTC.
Is the correct explanation?
The implementation seems to be vendor specific, however looking at the documentation of date parse we see that as of 1.8.5 javascript supports both RFC2822 dates and ISO 8601 dates.
As per the Date.UTC documentation ISO 8601 dates are assumed to be in UTC time if not otherwise specified and thus the timezone difference is automatically added.
RFC2822 dates seem to be assumed as local times and as such are not modified.
I cannot seem to replicate your results, but the results seem to differ from browser to browser.
See: http://jsfiddle.net/f7DMV/
In Firefox and Opera, I get only the middle line parsing correctly, the others are Invalid Dates.
In Chrome, both the first and the second line parse correctly (and don't differ), but the last one is still Invalid.
It will vary from browser to browser. The ECMA262 spec says any string which is not in YYYY-MM-DD format and is passed to the Date function, it may fall back to implementation-specific heuristics or implementation-specific date formats.

Categories

Resources