Reputation: 7012
I am having similar requirement as this: Convert time in HH:MM:SS format to seconds only?
but in javascript. I have seen many examples of converting seconds into different formats but not HH:MM:SS into seconds.
Upvotes: 149
Views: 212280
Reputation: 1
I suggest a variant without split function. It has many strings, but you can see what exactly code is doing. Possible formats "HH:MM:SS", "MM:SS", "SS" (with one or two digits). My code:
function timeToSeconds(str)
{
let result = 0;
let coef60 = 1;
let coef10 = 1;
let index = str.length-1;
// seek from right to left
while(index > -1)
{
let char = str[index];
if(char == ":")
{
coef60 *= 60;
coef10 = 1;
index--;
continue;
}
result += (char) * coef60 * coef10;
coef10 *= 10;
index--;
}
return result;
}
Upvotes: 0
Reputation: 96
This is very old question, but here is two liner very easy to understand answer and it works with any of the following format
hh:mm:ss or h:m:s
mm:ss or m:s
ss or s
function convertToSecs =(strTime){
let [s=0, m=0, h=0] = strTime.split(':').reverse();
return (+h) * 3600 + (+m) * 60 + (+s);
};
Upvotes: 3
Reputation: 1131
I would suggest a slightly different approach to most other answers here:
// Solution:
const hmsToSeconds = s => /^\d+:\d+:\d+$/.test(s) ? s.split(':').reduce((x, y) => x * 60 | y) : NaN;
// Test cases to check correctness:
`0:0:0
0:0:1
0:1:0
1:0:0
1:1:1
1:1
1
:1:1
1:1:f
foo`
.split('\n')
.forEach(s => console.log(`${s} = ${hmsToSeconds(s)}`));
This isn't just because it's fun to write your own little one-liner; I believe this is probably a safer option than the other answers most of the time.
There is a dangerous flaw in the logic behind the several answers saying e.g. 'this code will also handle mm:ss and ss!', in that it confidently assumes that when it consumes, say, '13:37'
that it should be reading '13 minutes & 37 seconds', rather than '23 minutes to 2'.
The opposite assumption would probably be the safer bet, I would personally have though. But ultimately it is best to not make any assumptions without actual solid basis in the actual sources of data the specific system is going to encounter. The last thing you want is a bad assumption like this in a tiny snippet of code buried deep in your codebase to go off like a landmine when months down the line data from a slightly different source starts failing silently.
This solution should pretty confidently reject anything not in the exact form '<int>:<int>:<int>'
and just evaluate to NaN
. This is likely to be noticed much sooner than the system (potentially intermittently!) be off in some calculations by a factor of 60.
Upvotes: 0
Reputation: 76736
Try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
Upvotes: 259
Reputation: 24244
This is the most clear, easy to understand solution:
function convertDurationtoSeconds(duration){
const [hours, minutes, seconds] = duration.split(':');
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds);
};
const input = '01:30:45';
const output = convertDurationtoSeconds(input);
console.log(`${input} is ${output} in seconds`);
Upvotes: 15
Reputation: 1630
Taken from the solution given by Paul https://stackoverflow.com/a/45292588/1191101 but using the old function notation so it can also be used in other js engines (e.g. java Rhino)
function strToSeconds (stime)
{
return +(stime.split(':').reduce(function (acc,time) { return +(60 * acc) + +time }));
}
or just this one more readable
function strToSeconds (stime)
{
var tt = stime.split(':').reverse ();
return ((tt.length >= 3) ? (+tt[2]): 0)*60*60 +
((tt.length >= 2) ? (+tt[1]): 0)*60 +
((tt.length >= 1) ? (+tt[0]): 0);
}
Upvotes: 1
Reputation: 19999
Here is maybe a bit more readable form on the original approved answer.
const getSeconds = (hms: string) : number => {
const [hours, minutes, seconds] = hms.split(':');
return (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds);
};
Upvotes: 8
Reputation: 6871
This can be done quite resiliently with the following:
'01:02:03'.split(':').reduce((acc,time) => (60 * acc) + +time);
This is because each unit of time within the hours, minutes and seconds is a multiple of 60 greater than the smaller unit. Time is split into hour minutes and seconds components, then reduced to seconds by using the accumulated value of the higher units multiplied by 60 as it goes through each unit.
The +time
is used to cast the time to a number.
It basically ends up doing: (60 * ((60 * HHHH) + MM)) + SS
If only seconds is passed then the result would be a string, so to fix that we could cast the entire result to an int:
+('03'.split(':').reduce((acc,time) => (60 * acc) + +time));
Upvotes: 67
Reputation: 51
new Date(moment('23:04:33', "HH:mm")).getTime()
Output: 1499755980000 (in millisecond) ( 1499755980000/1000) (in second)
Note : this output calculate diff from 1970-01-01 12:0:0 to now and we need to implement the moment.js
Upvotes: 2
Reputation: 11
This function works for MM:SS as well:
const convertTime = (hms) => {
if (hms.length <3){
return hms
} else if (hms.length <6){
const a = hms.split(':')
return hms = (+a[0]) * 60 + (+a[1])
} else {
const a = hms.split(':')
return hms = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])
}
}
Upvotes: 1
Reputation: 166
Convert hh:mm:ss
string to seconds in one line. Also allowed h:m:s
format and mm:ss
, m:s
etc
'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)
Upvotes: 15
Reputation: 2105
You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.
var str = '12:99:07';
var times = str.split(":");
times.reverse();
var x = times.length, y = 0, z;
for (var i = 0; i < x; i++) {
z = times[i] * Math.pow(60, i);
y += z;
}
console.log(y);
Upvotes: -1
Reputation: 47605
function parsehhmmsst(arg) {
var result = 0, arr = arg.split(':')
if (arr[0] < 12) {
result = arr[0] * 3600 // hours
}
result += arr[1] * 60 // minutes
result += parseInt(arr[2]) // seconds
if (arg.indexOf('P') > -1) { // 8:00 PM > 8:00 AM
result += 43200
}
return result
}
$('body').append(parsehhmmsst('12:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('1:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('2:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('3:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('4:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('5:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('6:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('7:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('8:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('9:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('10:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('11:00:00 AM') + '<br>')
$('body').append(parsehhmmsst('12:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('1:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('2:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('3:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('4:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('5:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('6:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('7:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('8:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('9:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('10:00:00 PM') + '<br>')
$('body').append(parsehhmmsst('11:00:00 PM') + '<br>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: -1
Reputation: 511
Since the getTime function of the Date object gets the milliseconds since 1970/01/01, we can do this:
var time = '12:23:00';
var seconds = new Date('1970-01-01T' + time + 'Z').getTime() / 1000;
Upvotes: 17
Reputation: 310
Javascript's static method Date.UTC()
does the trick:
alert(getSeconds('00:22:17'));
function getSeconds(time)
{
var ts = time.split(':');
return Date.UTC(1970, 0, 1, ts[0], ts[1], ts[2]) / 1000;
}
Upvotes: 5
Reputation: 26730
This function handels "HH:MM:SS" as well as "MM:SS" or "SS".
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0, m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
Upvotes: 98
Reputation: 4273
try
time="12:12:12";
tt=time.split(":");
sec=tt[0]*3600+tt[1]*60+tt[2]*1;
Upvotes: 11