javascript 如何判断传入的日期是否是今天

//PHP中直接这样使用就可以获取这一天0点0分0秒的时间

$dt = date('Y-m-d');

//javascript如何获取当天的时间

//目的是跟一个字符串比如 2014-7-8 2014-07-08做比较是否是同一天


function isToday(str){

    var d = new Date(str);

    if(d == new Date()){

        return true;

    } else {

        return false;

    }

}



console.log(isToday('2014-7-8'));

console.log(isToday('2014-07-08'));


HUWWW
浏览 2575回答 8
8回答

千万里不及你

javascript 似乎不能对2014-7-8这样的格式解析,要么带前缀0,要么“-”替换成“/”才能正确解析。function isToday(str){    var d = new Date(str.replace(/-/g,"/"));    var todaysDate = new Date();    if(d.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)){        return true;    } else {        return false;    }}console.log(isToday('2014-7-8'));console.log(isToday('2014-07-08'));

九州编程

只用JavaScript实现,举一个例子://javascript如何获取当天的时间function isToday(str){    var d = new Date();    var y = d.getFullYear(); // 2014    var m = d.getMonth() + 1; // 7,月份从0开始的,注意    var d = d.getDate(); // 9    var date_str = y + '-' + m + '-' + d;    return str == date_str; }console.log(isToday('2014-7-8'));

BIG阳

function isToday(date){&nbsp; &nbsp; var today=new Date(),&nbsp; &nbsp; &nbsp; &nbsp; //获取从今天0点开始到现在的时间&nbsp; &nbsp; &nbsp; &nbsp; todayTime=today.getTime()%(1000*60*60*24),&nbsp; &nbsp; &nbsp; &nbsp; //获取要判断的日期和现在时间的偏差&nbsp; &nbsp; &nbsp; &nbsp; offset=date.getTime()-today.getTime(),&nbsp; &nbsp; &nbsp; &nbsp; //获取要判断日期距离今天0点有多久&nbsp; &nbsp; &nbsp; &nbsp; dateTime=offset+todayTime;&nbsp; &nbsp; if(dateTime<0||dateTime>1000*60*60*24){&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }}isToday(new Date('2013-7-8'));isToday(new Date('2014-7-8'));isToday(new Date('2015-7-8'));isToday(new Date());isToday(new Date(123465));

慕妹3146593

首先用chrome的控制台试了一下 '2014-7-8'和 '2014-07-08'都可以解析成功导致题主这样子解析失败的是 引用对象用双等号判断地址而不是值return&nbsp;new&nbsp;Date(str).getTime()&nbsp;==&nbsp;new&nbsp;Date().setHours(0,&nbsp;0,&nbsp;0,&nbsp;0);

手掌心

function isToday(date){&nbsp; &nbsp; var today = new Date();&nbsp; &nbsp; today.setHours(0);&nbsp; &nbsp; today.setMinutes(0);&nbsp; &nbsp; today.setSeconds(0);&nbsp; &nbsp; today.setMilliseconds(0);&nbsp; &nbsp; var offset=date.getTime()-today.getTime()&nbsp; &nbsp; return offset>=0&&offset<=1000*60*60*24}

汪汪一只猫

Date对象有个toLocaleDateString方法可以获取日期部分的字符串,像这样:function isToday(date){&nbsp; &nbsp; var today = new Date().toLocaleDateString();&nbsp; &nbsp; var date = new Date(date).toLocaleDateString();&nbsp; &nbsp; return today == date;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript