自从/直到javascript的日期

时间:2014-06-23 02:51:37

标签: javascript date

我想做关于从/到的方法,但我担心月份发生变化时会出现错误。我不想计算何时离开或过去。

我的代码:

var graduatedDay = new Date();
var day = graduatedDay.getDate();
var month = graduatedDay.getMonth() + 1;
//(I plus one because month value is 0-11)
var year = graduatedDay.getFullYear();

if ((day >= 15 && month >= 3) || (month > 4) && year >= 2015) {
    document.write("Since today you have graduated");
} else {
    document.write("You aren't graduated yet");
}

我不确定上面的代码是否已经给出,但我有我的概念

3 个答案:

答案 0 :(得分:0)

如果您计算第3个月和第15天之后的年份,那么您不必检查该月>试试这个

if(((day>=15 && month>=3) || month > 4) && year >= 2015 )

答案 1 :(得分:0)

为什么不与另一个日期对象进行比较?

var graduatedDay = new Date();
var x = new Date('2013-03-15');
if (graduatedDay > x)
  {document.write("Since today you have graduated")} 
else
  {document.write("You aren't graduated yet")}

我相信您原始代码中可能出现的错误是(

if( day>=15 && month>=3 && year >= 2015 )

答案 2 :(得分:0)

使用日期对象会更简单(假设毕业日是2015-03-14):

var graduateDay = new Date(2015, 2, 14)
var today = new Date();

if (today > graduateDay) {
    document.write("Since today you have graduated");

} else {
    document.write("You aren't graduated yet");
}