最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check if the date is earlier than today - Stack Overflow

programmeradmin7浏览0评论
   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??

   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??

Share Improve this question edited Oct 29, 2012 at 13:29 user947462 asked Oct 29, 2012 at 13:24 user947462user947462 9496 gold badges18 silver badges28 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

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

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');

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.

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.

year of date2 is 0112 and of date1 is 2012

发布评论

评论列表(0)

  1. 暂无评论