Reputation: 1280
I have two <input type="time">
. By default, each input collects a time value as a string. For example, "08:30"
.
How can I convert this string into an object which would then enable computation? Is it possible to avoid involving the use of date
in this approach?
In the end, I would like to compute the difference between two time
strings and then return the result in minutes. For example, the expected return value of08:00
and 09:00
would be 60
minutes.
Upvotes: 0
Views: 500
Reputation: 146360
Just do it as if you only had pen and paper:
You can parse from string using regular expressions:
var parts = "08:45".match(/^(\d+):(\d+)$/);
console.log(+parts[1], +parts[2], +parts[1] * 60 + +parts[2]);
... and formatting back to string should not be very difficult either.
Upvotes: 2
Reputation: 772
Generally speaking I whould suggest using Date insted of using custom functions, but just for your case this is the example function:
const timeStart = "8:00:00";
const timeEnd = "8:10:00";
//Handles only time with format in hh:mm or hh:mm:ss
//For more complicated cases use Date
function diff(start, end) {
const startMinutes = getMinutes(start);
const endMinutes = getMinutes(end);
return endMinutes - startMinutes
}
function getMinutes(strTime) {
const time = strTime.split(':');
return (time[0] * 60 + time[1]*1);
}
alert(diff(timeStart, timeEnd));
Note that this function is not responsible for validation of the time difference only the computation. You should validate you input
Upvotes: 0
Reputation: 16779
Assuming you want to use a 24h clock:
function minutesBetween (a, b) {
return Math.abs(toMinutes(b) - toMinutes(a))
}
function toMinutes (time) {
time = /^(\d{1,2}):(\d{2})$/.exec(time)
return time[1]*60 + +time[2]
}
console.log(minutesBetween('8:30', '9:30')) //=> 60
Upvotes: 0