How to compare two datetime in javascript?

2020-04-21 02:38发布

问题:

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(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,


            }

else is not working ! There are truckOnline markers on google map.Where is my mistake ?

And LastRecordTime format like this in SQL : 04.12.2013 01:03:00

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

回答1:

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".



回答2:

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.



回答3:

I solved by SQL.

I set a new colum for difference minute between now and ReadTime.

    DifferenceMinute=DATEDIFF(MINUTE,ReadTime,GETDATE())



if(DifferenceMinute>10)

 { 

  bla bla

  }

 else 
 {

 bla bla

  }


回答4:

To compare dates with time in Javascript we need to pass them in Date object as "yyyy/mm/dd HH:mm" format for e.g. like "2014/05/19 23:20" . Then you can just compare them with > or < less then symbol according to your business rule. Please see given below code for more understanding.

$(function () {

    $("input#Submit").click(function () {
        var startDateTime = $("input[name='StartDateTime']").val();
        var endDateTime = $("input[name='EndDateTime']").val();

        var splitStartDate = startDateTime.split(' ');
        var splitEndDate = endDateTime.split(' ');

        var startDateArray = splitStartDate[0].split('/');
        var endDateArray = splitEndDate[0].split('/');

        var startDateTime = new Date(startDateArray[2] + '/ ' + startDateArray[1] + '/' + startDateArray[0] + ' ' + splitStartDate[1]);
        var endDateTime = new Date(endDateArray[2] + '/ ' + endDateArray[1] + '/' + endDateArray[0] + ' ' + splitEndDate[1]);

        if (startDateTime > endDateTime) {
            $("#Error").text('Start date should be less than end date.');
        }
        else {
            $("#Error").text('Success');
        }
    });

});

You can also see a working demo here