Convert string to datetime in javascript and compare with current time

Mudassir Hasan picture Mudassir Hasan · Dec 19, 2014 · Viewed 28.1k times · Source

I am trying to pick up value from datetimepicker tetxbox and compare those values with current time.

JSFiddle

        //startTime textbox text = 19/12/2014 03:58 PM
        var startTime = Date.parse($('[id$=txtStartDate]').val().toString());

        //endTime textbox text = 19/12/2014 04:58 PM
        var endTime = Date.parse($('[id$=txtEndDate]').val().toString());

        var currentTime = Date.now();
        alert(startTime);
        alert(endTime);
        alert(currentTime);

        if (currentTime >= startTime && currentTime <= endTime) {
              alert();

        }

Date.parse() is used fro converting string to milliseconds since Jan 1 1970. Date.now() returns current date milliseconds since Jan 1 1970.

But the above conversion methods are not working properly. What should be logic to compare datetime by first sonverting string in format like 19/12/2014 03:58 PM to Date object and then do comparing.

Answer

T.J. Crowder picture T.J. Crowder · Dec 19, 2014

Since that format isn't documented as being supported by Date.parse, your best bet is to parse it yourself, which isn't difficult: Use String#split or a regular expression with capture groups to split it into the individual parts, use parseInt to convert the parts that are numeric strings into numbers (or, with controlled input like this, just use the unary + on them), and then use new Date(...) to use those numbers to create a Date instance.

One gotcha: The month value that new Date expects is zero-based, e.g. 0 = January. Also remember to add 12 to the hours value if the input uses AM/PM instead of the 24-hour clock.


Or, of course, use any of several date/time handling libraries, such as MomentJS.