1

我有一个我无法解决的简单问题。下面的代码在 chrome 中运行良好,但在其他浏览器中出现 NaN 错误......

function chkdate()
{

  var todayDate=new Date();
  var date=todayDate.getDate();
  if( date<10)
  {
  date= "0"+date;
   }
  var month=todayDate.getMonth()+1;
 if( month<10)
 {
  month= "0"+month;
  }

 var year=todayDate.getFullYear();

 var hours=todayDate.getHours();
if( hours<10)
{
hours= "0"+hours;
}


 var curdate =  year+"-"+month+"-"+date+"  "+hours+":00:00"  ;

 alert(curdate);
 var curtime= new Date(curdate).getTime();
 alert("current timestamp = "+  curtime) ;      //   <----     **This gives NaN error .**   
4

2 回答 2

2

为什么不使用Date()'s 构造函数之一构造日期?

var curtime = new Date(year, month, date, hours).getTime();

这应该是跨浏览器的,因为您不依赖字符串解析来构造日期对象。

于 2012-10-17T06:29:06.473 回答
0

尝试获取当前时间时格式不正确

var curdate =  year+"-"+month+"-"+date;

 alert(curdate);
 var curtime= new Date(curdate).getTime();
 alert("current timestamp = "+  curtime) ;      //   <----     **This will not give you NaN error .** 
于 2012-10-17T06:56:34.417 回答