Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date from string giving different output from Chrome to Firefox

I'm trying to write some javascript code to format a date as I want, but I have troubles making it work on Firefox (it's working as I want on Chrome).

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

For that, what I did is 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 on both browsers here : http://jsfiddle.net/j4BLH/

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

I know I could've written something like "20" + startDate.getYear() but I was wondering why the results were different from Chrome to Firefox ? And maybe if you have a better way of writing the code I pasted here, please let me know :)

Thanks !

like image 441
B F Avatar asked May 14 '13 08:05

B F


People also ask

How to parse date into string in JavaScript?

The toString() method returns a date object as a string.

What is toUTCString()?

The toUTCString() method converts a date to a string, interpreting it in the UTC time zone. Based on rfc7231 and modified according to ECMA-262 toUTCString, it can have negative values.


1 Answers

From the spec:

However, the expression Date.parse(x.toLocaleString()) is not required to produce the same Number value as the preceding three expressions and, in general, the value produced by Date.parse is implementation-dependent when given any String value that does not conform to the Date Time String Format (15.9.1.15) and that could not be produced in that implementation by the toString or toUTCString method.

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

Your date format, using a 2 digit year, is not conforming to the standard. As such, it would seem that the way these dates are parsed is implementation specific, meaning that it depends upon the Javascript engine being used. In Google's case, it's usually V8, and in Firefox, it's TraceMonkey or Rhino I believe.

In short, you should really use 4 digit years, as there is no YY in the JS standard.

like image 124
MasNotsram Avatar answered Oct 25 '22 02:10

MasNotsram