jquery convertion from string to time
31,068
Solution 1
You can parse the time with this:
function timeToSeconds(time) {
time = time.split(/:/);
return time[0] * 3600 + time[1] * 60 + time[2];
}
It returns a number of seconds since 00:00:00, so you can compare the results easily:
timeToSeconds('06:53:22') < timeToSeconds('19:23:58')
Solution 2
var startTime = "19:23:58";
var endTime = "06:53:22";
var startDate = new Date("1/1/1900 " + startTime);
var endDate = new Date("1/1/1900 " + endTime);
if (startDate > endDate)
alert("invalid time range");
else
alert("valid time range");
js is smart enough to figure it out :)
Solution 3
of course you can do it, but before you should parse this string. date = new Date(year, month, day, hours, minutes, seconds, milliseconds)
- we creaeted new object. After we can use date.getTime()
date.getFullYear
..
Author by
sisko
Professional web developer making the transition into Robotics
Updated on May 11, 2020Comments
-
sisko about 4 years
I have a system in development which records various times of the day in the following format: 06:53:22 or 19:23:58 as examples.
Can anyone tell me if it is possible to convert this string into javascript construct which I can use to compare times of the day?
-
Ivan over 10 yearsI see a mistake. Function returns string except int. To fix this we need to use: return time[0] * 3600 + time[1] * 60 + time[2] * 1;
-
Nic over 9 yearsGreat, Thanks Joseph.