user947462
user947462

Reputation: 949

check if the date is earlier than today

   alert(date2);//Sat Oct 29 0112 00:00:00 GMT+0100 (GMT Daylight Time) 
   alert(date1);//Fri Oct 12 2012 00:00:00 GMT+0100 (GMT Daylight Time)

if (date1.getTime()<date2.getTime()) {
     alert('your date can not be earlier than today.');
}

My question is why i don't see the alert? There is something wrong?

edit:

var today = new Date();
date2 = new Date(today.getYear(), today.getMonth(), today.getDate());

why this show the year as 0112??

Upvotes: 0

Views: 4001

Answers (5)

Himanth Kumar
Himanth Kumar

Reputation: 316

First you split both dates as different values for its month, day and year. You may use an array of months to find out the number for month. Then:

var date1 = new Date;
var date2 = new Date;
date1.setDate(29);
date1.setMonth(10);
date1.setFullYear(2012);

date2.setDate(12);
date2.setMonth(10);
date2.setFullYear(2012);

if(date1>date2)
alert('Date1 is greater');
else
alert('Date2 is greater');

Upvotes: 3

Lee Taylor
Lee Taylor

Reputation: 7984

Use getFullYear(), not getYear().

On some implementations getYear() returns the number of years since 1900. This is why you are getting 112 for the year.

Upvotes: 2

iJade
iJade

Reputation: 23791

year of date2 is 0112 and of date1 is 2012

Upvotes: 0

Jon Taylor
Jon Taylor

Reputation: 7905

Well date 1 is in 2012 and date 2 is in 0112 so date 2 is before date 1, hence why you are not seeing the alert.

Upvotes: 0

Jonathan Muller
Jonathan Muller

Reputation: 7516

Your date 1 is in year 2012 and your date2 is in year 112, you test if date1 is inferior to date2. Year 2012 is superior to year 112, so nothing is wrong here

Upvotes: 3

Related Questions