日期格式和比较日期

时间:2012-05-28 09:51:09

标签: javascript date

我想检查日期是否在今天之前。如果是,那么我想显示日期而不是时间,如果是今天,那么我想显示时间而不是日期。我检查的日期是dd-mm-yyy hh:mm格式,因此它们不进行比较。

到目前为止,请查看我的内容:

var created = '25-05-2012 02:15';
var now = new Date();

if (created < now) { 
  created_format = [ format the date to be 25-05-2012 ]
} else {
  created_format = [ format the date to be 02:15 ]
}

我在其他示例中看到这些之后尝试使用now.dateFormat()now.format(),但我收到“不是函数”错误消息。

2 个答案:

答案 0 :(得分:1)

首先获取日期字符串的部分:

var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date(); 

// Test if it's today    
if (bits[0] == now.getDate() &&
    bits[1] == (now.getMonth() + 1) &&
    bits[2] == now.getFullYear() ) {

  // date is today, show time

} else {
  // date isn't today, show date
}

当然还有其他方法,但我认为以上是最简单的方法。 e.g。

var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
  // otherDate is before today
} else {
  // otherDate is not before today
}

同样,将字符串转换为日期后,您可以使用getFullYeargetMonthgetDate进行相互比较,但这与第一种方法基本相同

答案 1 :(得分:0)

您可以使用getTime方法获取时间戳。然后,您可以将其与当前日期时间戳进行比较。

相关问题