Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  147] [ 2]  / answers: 1 / hits: 34158  / 10 Years ago, fri, december 19, 2014, 12:00:00

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.


More From » jquery

 Answers
6

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.


[#68438] Tuesday, December 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hadens

Total Points: 142
Total Questions: 98
Total Answers: 100

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;