Javascript Date from string giving different results from Chrome to Firefox.

I am trying to write javascript code to format the date as I want, but I have problems working on Firefox (it works the way I want in Chrome).

The input that I have is 05/01/13 (mm / dd / yy) and I want 2013-05-01 (yyyy / mm / dd).

For this, I did something like this:

 var formDate = document.getElementById("start").value; var myDate = new Date(formDate); var startDate = new Date(); startDate.setMonth(myDate.getMonth() + 1); startDate.setFullYear(myDate.getFullYear()); var FormattedDate = startDate.getFullYear() + "-" + ((startDate.getMonth() <= 10) ? "0" : "") + startDate.getMonth() + "-01"; // the day is always 01 alert(FormattedDate); 

You can try it in both browsers here: http://jsfiddle.net/j4BLH/

In Google Chrome, this code gives me, for example, 2013-05-01 in May, but in Firefox I have 1913-05-01 .

I know I could write something like "20" + startDate.getYear() , but I was wondering why the results are different from Chrome for Firefox? And maybe if you have a better way to write the code that I inserted here, let me know :)

Thanks!

+6
source share
1 answer

From spec :

However, the Date.parse expression (x.toLocaleString ()) is not required to get the same number value as the previous three expressions and, in general, the value created by Date.parse is implementation dependent if any String value is given that is not match the format of the date time string (15.9.1.15), and this cannot be done in this implementation using the toString or toUTCString Method.

When creating a date object by passing the date string to the constructor, the parsing method is exactly the same as Date.parse.

The format of your date, using a 2-digit year, is not standard. Thus, it would seem that the way these dates are analyzed is implementation-specific, which means that it depends on the Javascript mechanism used. In the case of Google, this is usually V8, and in Firefox it is TraceMonkey or Rhino, I think.

In short, you really should use 4-digit years since the JS standard does not have YY.

+5
source

Source: https://habr.com/ru/post/944953/


All Articles