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?
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.
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With