小编典典

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

sql

我尝试通过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)

阅读 190

收藏
2021-04-14

共1个答案

小编典典

穆罕默德

看来您打错了字:

  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”。

2021-04-14