How to compare two datetime in javascript?
datetime-format, javascript, sql
Solution
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".
Problem
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) ```