Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript AM/PM time comparison

Suppose I have 2 datetime variables:

var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";

I want to compare these 2 datetimes. How can I get Javascript to recognize whether the time is AM or PM?

I think Javascript will compare the time in 24 hours format. Do I need to convert the time to 24 hour format? Is that correct? Could someone please suggest the correct solution....

like image 796
Dylan Avatar asked Jun 02 '13 07:06

Dylan


1 Answers

Just use straight javascript functions

var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";
var from = new Date(Date.parse(fromdt));
var to = new Date(Date.parse(todt));

alert(from);
alert(to)

if (from > to) alert("From");
else alert("To");

Once the date is parsed into date form, you can do what you like with it. And you can compare dates using the standard operator signs ( >, < etc)

I'm not sure what you need to do with them, but http://www.w3schools.com/jsref/jsref_obj_date.asp is an okay reference.

And heres a crappy sandbox with the above code http://jsfiddle.net/QpFcW/

and a better one that XX deleted :( http://jsfiddle.net/QpFcW/1/

like image 173
monkeyhouse Avatar answered Sep 24 '22 20:09

monkeyhouse