Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Date.parse not return a Date object?

Tags:

javascript

today1 = new Date();
today2 = Date.parse("2008-28-10");

To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.

if (today1.getTime() == today2)

Why is this?

like image 201
ProfK Avatar asked Oct 28 '08 09:10

ProfK


3 Answers

To answer the question in the title: Because they decided so when creating the JavaScript language. Probably because Java's java.util.Date parse function was doing the same thing, and they wanted to mimic its behavior to make the language feel more familiar.

To answer the question in the text... Use this construct to get two date objects:

var today2 = new Date(Date.parse("2008-10-28"));

EDIT: A simple

var today2 = new Date("2008-10-28");

also works.


Note: Old Internet Explorer versions (anything before 9) does not understand dashes in the date string. It works with slashes, though:

var today2 = new Date("2008/10/28");

Slashes seem to be universally understood by browsers both old and new.

like image 87
Tomalak Avatar answered Oct 09 '22 06:10

Tomalak


If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same.

Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date object itself. If you want to hold the Date object itself, just build it like so:

var newDate = new Date();
newDate.setFullYear(2008,9,28);

For more reference check out: the Date class reference

like image 39
Yuval Adam Avatar answered Oct 09 '22 06:10

Yuval Adam


I can't answer in place of the language designers, but you can use the result of Date.parse or Date.UTC in the Date constructor to get such object.

Note that your code sample is incorrect: it is not a valid date format, not ISO (yyyy-mm-dd) nor IETF (Mon, 25 Dec 1995 13:30:00 GMT+0430 ). So you will get a NaN. Date.parse only understand IETF format, from what I have read on MDC.

If you need to compare two dates, you might compare the results of .getFullYear(), .getMonth() and .getDay(), or just compare the string representations at the wanted level.

var d1 = new Date();
var n = Date.parse("28 Oct 2008");
var d2 = new Date(n);
var d3 = new Date("28 october 2008");

alert(d1.toDateString() == d2.toDateString());
alert(d2.toDateString() == d3.toDateString());
like image 25
PhiLho Avatar answered Oct 09 '22 06:10

PhiLho