How to compare two datetime in javascript?

后端 未结 4 1581
情书的邮戳
情书的邮戳 2021-01-22 23:48

I tried create markers by JSON parse from C #.I have a small problem about datetime compare in javascript.

  var nowDate= new Date();

  var LastTenMin= new Date         


        
4条回答
  •  执念已碎
    2021-01-23 00:12

    Mehmet,

    Looks like you made a typo:

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

    Should be (note the comma):

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

    Also you were trying to create a new date object from a date object, this is incorrect:

     new Date(LastTenMin)
    

    And here is a more complete solution:

    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
    

    Here is the solution without comments:

    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
    

    My whole solution is assuming that the string contained in data2.LastRecordTime is in the format: "MM.DD.YYYY HH:MM:SS".

提交回复
热议问题