I have two strings:
var string1 = "01/02/2013 22:13";
var string2 = "08/01/2013 02:01";
I want convert to date in JavaScript to compare 2 dates.
I have two strings:
var string1 = "01/02/2013 22:13";
var string2 = "08/01/2013 02:01";
I want convert to date in JavaScript to compare 2 dates.
Don't prefer Date
object to be used to parse your date string. Instead do it yourself like this.
Here below I have written a method to parse your string to Date
function convertToDate(datSt) {
var s1 = datSt.split(" ");
var s1dat = s1[0].split("/");
var s1Tim = s1[1].split(":");
return new Date(s1dat[2], s1dat[1], s1dat[0], s1Tim[0], s1Tim[1])
}
Using Date.getTime()
which returns you the millisecond, so that you can perform your Date comparison very easily.
if (d1.getTime() > d2.getTime()) {
//do whatever
} else if (d1.getTime() < d2.getTime()) {
//do whatever
} else {
//do whatever
}
Finally,
var string1 = "01/02/2013 22:13";
var string2 = "08/01/2013 02:01";
var d1 = convertToDate(string1);
var d2 = convertToDate(string2);
//getTime returns milliseconds, which can used for comparison
if (d1.getTime() > d2.getTime()) {
//do whatever
} else if (d1.getTime() < d2.getTime()) {
//do whatever
} else {
//do whatever
}
// Below is the method to split your string to Date object
function convertToDate(datSt) {
var s1 = datSt.split(" ");
var s1dat = s1[0].split("/");
var s1Tim = s1[1].split(":");
return new Date(s1dat[2], s1dat[1], s1dat[0], s1Tim[0], s1Tim[1])
}
FYI: You can't perform equity(==
) operation with Date objects. others(>
and <
) can be performed, follow this comment to know the reason.
If you wish to use plugin, I would prefer moment.js for a simple parsing.
Parsing date strings in JS is hard. First you need to know what format the string represents - the ones you posted are ambiguous. Libraries like http://momentjs.com/docs/#/parsing/ can help with various unambiguous forms. Definitely use a library because this stuff is tricky and browser's are inconsistent in how they implement 'standard' functions like Date.parse
var date1 = new Date(string1); //Turn it into a date
var date2 = new Date(string2); //Turn the other thing into a date
console.log(Math.abs(date1 - date2)); //Take the absolute value of the subtraction
As @RobertLevy points out, this might not work depending on the culture of the user. (D/M/Y vs M/D/Y), so it is preferred that you deal with all dates server-side, so the browser only gets the (correct) timestamp.