Convert string to datetime in javascript and compare with current time

36.3k views Asked by At

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.

3

There are 3 answers

0
T.J. Crowder On BEST ANSWER

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.

0
Abdallah Arffak On

You should use this method

var startTime  = new Date(year, month, day, hours, minutes, seconds, milliseconds);

this a demo http://jsfiddle.net/hswp7x8k/

to extrat value from string you can use this method

dd = '19/12/2014 03:58';
dd.match(/(\d+)\/(\d+)\/(\d+)\s*(\d+):(\d+)/);

this a demo http://jsfiddle.net/w3wow1ay/2/

0
Johan Karlsson On

The problem is Date() expects date format mm/dd/yyyy, so your date is invalid.

You can fix your date like this:

function toValidDate(datestring){
    return datestring.replace(/(\d{2})(\/)(\d{2})/, "$3$2$1");   
}

var startTime = Date.parse(toValidDate($('[id$=txtStartDate]').val().toString())); 
var endTime = Date.parse(toValidDate($('[id$=txtEndDate]').val().toString()));    
var currentTime = Date.now();

alert(startTime);
alert(endTime);
alert(currentTime);

DEMO: http://jsfiddle.net/3mztdaja/3/