给定一个日期/时间字符串,例如:
2010-12-12 19:27:00Z
使用 JS/jQuery 如何轻松确定是否是今天?
谢谢
如果您的日期始终采用这种格式:
YYYY-MM-DD HH:mm:SSZ
然后应该这样做:
var input = '2010-12-12 19:27:00Z';
var year = parseInt(input.substring(0, 4), 10);
var month = parseInt(input.substring(5, 7), 10);
var day = parseInt(input.substring(8, 10), 10);
var d = new Date();
if(d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day) {
// It's today
} else {
// It's not
}
您可以使用Date.parse
将字符串转换为时间戳new Date
以将字符串解析为Date
对象。
var date = '2010-12-12 19:27:00Z',
// then = new Date(Date.parse(date)),
then = new Date(date),
// Firefox doesn't support dates in this format
// you can covert it to an accepted format like this:
// then = new Date(date.replace(/(.*) (.*)Z/,'$1T$2'))
now = new Date;
然后你可以比较日期。
if(then.toDateString() === now.toDateString())
像这样的东西应该可以工作,尽管这假设月份和日期字段将始终为 2 位数字。
var dateInput = "2010-12-12 19:27:00Z"
var date = dateInput.substring(0, 10); //"2010-12-12"
var d = new Date();
var today = d.getFullYear() + "-" + ( d.getMonth() + 1 ) + "-" + d.getDate();
if( date == today )
match = true;
else
match = false;
var input = new Date('2012-06-07 19:27:00Z');
var curr = new Date();
var iDate = input.getDate+'-'+input.getMonth()+'-'+input.getFullYear();
var currDate = curr.getDate+'-'+curr.getMonth()+'-'+curr.getFullYear();
if(iDate== currDate){
console.log("today");
}else{
console.log("not");
}
这是演示