Reputation: 9910
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?
Upvotes: 4
Views: 34735
Reputation: 99929
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')
Upvotes: 11
Reputation: 43
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
..
Upvotes: 1
Reputation: 78590
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 :)
Upvotes: 7