How to compare two datetime in javascript?

后端 未结 4 1582
情书的邮戳
情书的邮戳 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:11

    This is going to sound like a cop out, but I would switch to MomentJS so you get the following code:

    var Time1 = moment("04/12/2013 01:03:00");
    var lastTenMin = moment().subtract({minutes: 10});
    
    if(Time1.isBefore(lastTenMin)){
        image2 = '/Images/truckOnline.png';
        status = "Truck is online."+"\n"+"Last seen:"+" "+Time1.local();
    } else {
        image2 = '/Images/truckOffline.png';
        status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1.local();
    }    
    

    Remember, JavaScript has random off-by-one issues for the date and month (one is zero-based, the other is one-based). The problem most likely is in this line:

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

    If you switch to MomentJS, these kind of problems will disappear. I have lost many hours fighting these same issues, so I understand!

    P.S. Try out the calendar() formatting feature... it may be a good fit in your UI.

提交回复
热议问题