Javascript Date.parse bug when dash-delimited and starts with year - javascript

Am seeking confirmation if this is a bona fide documentation and/or implementation bug with Javascript's Date.parse method.
The docs I'm referring to are at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse and they say 'If you do not specify a time zone, the local time zone is assumed.'
But the following code shows that, despite not specifying a time zone, local time is not being assumed (but rather my timezone offset is being applied), if the string passed to Date.parse begins with the 4-digit year representation, and is dash-delimited.
var euroStyleDate = '2011-10-04';
var amerStyleDate = '10/04/2011';
var euroStyleParsed = Date.parse(euroStyleDate);
var amerStyleParsed = Date.parse(amerStyleDate);
console.log(euroStyleParsed); //1317686400000
console.log(amerStyleParsed); //1317700800000
console.log(new Date(euroStyleParsed));
//Date {Mon Oct 03 2011 20:00:00 GMT-0400 (Eastern Daylight Time)}
console.log(new Date(amerStyleParsed));
//Date {Tue Oct 04 2011 00:00:00 GMT-0400 (Eastern Daylight Time)}
There may even be other cases, and I'm sure I'm not the first to discover this if I am incorrect. So beyond confirmation, I'd surely love to be pointed at more in-depth information on this if anybody knows of pertinent links.
I'm experiencing this in FF3, Chrome for Windows and of course just to be special IE8 doesn't even seem to able to perform the conversion on 2011-10-04 whatsoever: I'm just getting an empty string in my application
Thanks in advance for any further insight or resources.

I ran into this concept, too. For anyone googling "Javascript dates dashes slashes" like I was, this is the clearest demonstration that I can think of as to what's going on here.
In short, slashes means local time zone, and dashes means UTC. Other answers has explanations regarding why.
<script type="text/javascript">
var
testB = new Date("2012/02/09"),
testC = new Date("2012-02-09");
alert(testB.toString());
alert(testC.toString());
alert(testC.toUTCString());
</script>

**Update:**It looks like there are several different standards at work here:
The EMCAScript < 5 standard allowed for dates in the standard IETF format, e.g. Sun Oct 03 2010. With these dates, the local timezone is assumed.
In ECMAScript 5, a limited version of the ISO 8601 standard is also allowed, e.g. 2010-10-03. The spec seems to say (perhaps following ISO 8601?) that in this case, the UTC timezone is assumed if one is not specified.
I haven't found a spec that says Date.parse can handle mm/dd/yyyy dates, but my browser (Chrome 14) clearly can, and probably other browsers can too. This appears to follow standard 1 above, assuming the local timezone. Given that it's not in the spec, however, I would recommend not using this version, as it's likely to be browser-dependent (and I have no idea whether 10-03-2010 would result in a different date if I had a European locale set on my browser).
There are a few issues with the native Date.parse function in most interpreters - I have often had timezone issues like the one you describe. So in general, I either use a library like Datejs or I write my own parsing functions. The DateTime module of the SIMILE AJAX library has a pretty good example function for parsing ISO-8601 dates (what you're referring to as euroStyleDate, plus an optional time component).
When setting dates, I generally use new Date() and then use the setUTC*() functions to set the different date elements to my desired precision. It's not perfect, but at least you're dealing with a clear timezone.

Related

String to date converter issue in js

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');

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')

Chrome & Firefox Date function different. (new Date)

new Date
when I use the date function in chrome I get something like this
Thu Jul 16 2015 20:37:47 GMT-0700 (Pacific Daylight Time)
when I do the same function in firefox I get this
2015-07-17T03:29:03.110Z
why are they different? I googled for a bit and search on stack but even the examples they were using to show their problem were comparing two dates of the same format. What I'd really like to know is why are they different now and how can I go about making them the chrome format cross as many browsers as possible?
Thanks
Resolved with moment.js
Firefox is in fact giving a different date string, and not simply displaying is differently as stated by Xufox.
The function I am going to use is
moment(new Date()).format("YYYY MMM D H:mm:ss")
but I will change around the .format, just wanted to get the answer here in case others run into the same problem
EDIT!!!!:
Xufox was right. I was a dummy. I had to manually edit some code in my timeline feed to get it going. I needed to use Date.parse on my generic time string, do my editing to the time, then use new Date. Thanks Xufox.

How to validate date in chrome browser as well as in firefox browser

In chrome I am trying to check date if it is valid date or not.
In have a variable:
var d = new Date('9/'); // Not a correct format
In Chrome
console.log(new Date('9/')); // Output: Sat Sep 01 2001 00:00:00 GMT+0530 (India Standard Time) Which is wrong as I am providing wrong date.
In Firefox
console.log(new Date('9/')); // Output: Invalid Date
Also using date.toLocaleString() has output 06 May 2007 00:00:00 in firefox
and in chrome it is 1/9/2001;
So my question is how to validate date in chrome and keep code safe from these differences. If need more details about it please write in comment.
The Javascript Date API can have somewhat mixed results between browsers, as you've discovered.
The best option I can suggest is to use one of the third-party libraries that are available for this. There are two I can recommend -- either Moment.js or Date.js.
Both of these libs have much better validation and parsing, and are more consistent cross-browser than the built-in Date class.
The correct answer is to use a Javascript library as #Spudley suggested like moment.js.
However, if you don't want to include that awesome library (or another like it), you could try running your date through a regex like this:
var date = "9/",
pattern = /(?:(?:\d{2}[-\/]){2}\d{4})|(?:\d{4}(?:[-\/]\d{2}){2})/,
isValid = false;
isValid = pattern.test( date );
This will match yyyy/mm/dd, dd/mm/yyyy, mm/dd/yyyy and yyyy/dd/mm (plus a number of variations [and issues]).
However, this is extremely naive, doesn't match the vast majority of date formats, allows mixed separators, and a wide array of other issues.
Again, I strongly recommend you implement a library like moment.js, but this regex might be a start.

Representing a date in JavaScript when timezone is irrelevant

I am working on a very small JavaScript library that allows users to retrieve content based on date. For this content, the date is just an identifier and timezones are completely irrelevant (think along the lines of a Dilbert flip calendar). The "May 14th" content is the same whether you are in the United States or Australia.
The function for retrieving data currently takes a Date object as a parameter. Within the function, the timezone is ignored. Does this approach make sense, or would it be better to take a timezone-independent identifier (like 2012-01-01) as a parameter instead? With the Date object approach, do I run the risk of returning the wrong data as a result of timezone adjustments browsers make?
How about using Date.getUTC*() functions? UTC time is the same for everyone.
After doing some research, it appears that simply ignoring the timezone information is the best approach. Why? This will always preserve the date and time that were provided to the Date constructor (which is my goal), whereas the getUTC* methods will return altered versions of the date and time. For example, take a look at this node REPL session I ran on a computer in the Eastern Time zone.
> d = new Date(2013, 03, 27, 23, 00, 00)
Sat Apr 27 2013 23:00:00 GMT-0400 (EDT)
> d.getDate() // The same date provided in the constructor. Woo!
27
> d.getUTCDate() // A different date. Boo!
28
Long story short, if you want to read the exact date and time that were provided in the Date constructor, using the normal get* methods (like getDate) will do that. If you use the getUTC* methods (like getUTCDate) modified versions of the date and time will be returned.
I know this may sound rudimentary to some of the more experienced programmers out there, but this really helped me make sense of things. I hope it helps others who come along.
The only problem with the approach in your own answer is that it doesn't account for ambiguous times. This happens during daylight savings fall-back transitions.
For example, set your computer's time zone to US Mountain Time ("Mountain Time (US & Canada)" on windows, or "America/Denver" on mac/linux). Then restart your browser and run the following javascript:
var dt = new Date(2013,10,3,1,0);
alert(dt);
This is November 3rd, 2013 at 1:00 AM. But you don't know which 1:00 AM it is representing. Is it in Mountain Daylight Time (UTC-6) before the transition, or Mountain Standard Time (UTC-7) after? There's no way to tell, and JavaScript will just use the standard time.
Now if all you need is 2013-11-03 01:00 - then you are correct. You can just ignore the offset and be done with it. But if you are going to use that value for anything meaningful - such as recording a point in time, or subtracting from another point in time for duration between them, then you have a problem that you can't resolve without the offset.
Unfortunately, there is no great solution for this problem in JavaScript. The closest thing is Moment.js, but it is still not perfect yet. Still, it is better than the Date object by itself, because it gets around browser inconsistencies and provides better parsing and formatting.

Categories

Resources