编程语言
首页 > 编程语言> > 如何在JavaScript中比较两个日期时间?

如何在JavaScript中比较两个日期时间?

作者:互联网

我尝试通过C#的JSON解析创建标记.关于javascript中的日期时间比较,我有一个小问题.

  var nowDate= new Date();

  var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);

 var Time1= data2.LastRecordTime;

 var image2;

  var status;


  if (new Date(Time1) < new Date(LastTenMin)) {


  image2 = '/Images/truckOnline.png';


   status = "Truck is online."+"\n"+"Last seen:"+" "+Time1,

   }

 else {


   image2 = '/Images/truckOffline.png';
   status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1,


            }

否则不起作用!谷歌地图上有truckOnline标记.我的错误在哪里?

和在SQL中这样的LastRecordTime格式:04.12.2013 01:03:00

    LastRecordTime=CONVERT(VARCHAR(10), [ReadTimeColumn], 104) + ' ' + CONVERT(VARCHAR(8), [ReadTimeColumn],108)

解决方法:

穆罕默德,

看来您打错了字:

  var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes(),- 10);

应该是(请注意逗号):

  var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes() - 10);

另外,您试图从日期对象创建新的日期对象,这是不正确的:

 new Date(LastTenMin)

这里是一个更完整的解决方案:

var nowDate= new Date();
var Time1 = new Date("04/12/2013 01:03:00");
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);

// Should return true 
console.log(Time1 < LastTenMin);

// Change the year to a point in the future
Time1 = new Date("04/12/2014 01:03:00");

// Shold return false
console.log(Time1 < LastTenMin);

// So your original conditional should look like this:
if (Time1 < LastTenMin) {
    image2 = '/Images/truckOnline.png';
    status = "Truck is online."+"\n"+"Last seen:"+" "+Time1;
} else {
    image2 = '/Images/truckOffline.png';
    status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1;
}

// And a more concise form:
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1

这是没有评论的解决方案:

var nowDate= new Date();
var Time1 = new Date(data2.LastRecordTime);
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1

我的整个解决方案假定data2.LastRecordTime中包含的字符串的格式为:“ MM.DD.YYYY HH:MM:SS”.

标签:javascript,sql,datetime-format
来源: https://codeday.me/bug/20191013/1910479.html