What the best way to convert the following starts playing time (1h20m25s) to second using javascript.
MODIFIED!
var hms = '1h20m00s',
H = hms.split('h')[0],
M = hms.substring(
hms.lastIndexOf("h") + 1,
hms.lastIndexOf("m")
),
S = hms.substring(
hms.lastIndexOf("m") + 1,
hms.lastIndexOf("s")
);
var spt = parseInt(H) * 60 * 60 + parseInt(M) * 60 + parseInt(S);
console.log(spt);
Not a clear question, hope this will help you :
// Assuming time is always in 99h99m99s format
var time = "1h20m25s";
// Extract hours
var h = parseInt(time.split("h")[0]);
var theRest = time.split("h")[1];
// Extract minutes
var m = parseInt(theRest.split("m")[0]);
// Extract seconds
var s = parseInt(theRest.split("m")[1]);
// Converting to seconds
var result = h*3600 + m*60 + s
document.write(time + ' in seconds : ' + result)
Related
how can I sum hours:minutes:seconds in JavaScript.
I mean by
04:32:05
03:14:03
To get
07:46:08
Ive tried
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
hour = parseInt(splitTime1[0]) + parseInt(splitTime2[0]) + parseInt(splitTime3[0]) + parseInt(splitTime4[0]) + parseInt(splitTime5[0]) + parseInt(splitTime6[0]) + parseInt(splitTime7[0])
minute = parseInt(splitTime1[1]) + parseInt(splitTime2[1]) + parseInt(splitTime3[1]) + parseInt(splitTime4[1]) + parseInt(splitTime5[1]) + parseInt(splitTime6[1]) + parseInt(splitTime7[1])
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2]) + parseInt(splitTime2[2]) + parseInt(splitTime3[2])
+ parseInt(splitTime4[2]) + parseInt(splitTime5[2]) + parseInt(splitTime6[2]) +
parseInt(splitTime7[2])
minute = minute + second/60;
second = second%60;
console.log(hour+ ":" + minute + ":"+ second)
The output I get is 8.4:24.183333333333334:11 instad of 08:24:11
any suggestions?
your making it very complex, you can reduce this by converting into Date objects and then add each date to get the sum of all dates
Understanding Date and Time in JavaScript
The problem with your code is you are including the decimal point
hour = hour + minute/60;
you need to floor it.
hour = hour + Math.floor(minute/60);
Now how to do it without a lot of repetitive code.
function toSeconds(s) {
const parts = s.split(':');
return +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
}
function secondsToHHMMSS(secs) {
return Math.floor(secs / 3600).toString().padStart(2, '0') + ':' +
(Math.floor(secs / 60) % 60).toString().padStart(2, '0') + ':' +
(secs % 60).toString().padStart(2, '0');
}
const timestamps = ["01:00:01", "01:00:10", "01:54:00", "01:30:00", "01:00:00", "01:00:00", "01:00:00"];
const totalSeconds = timestamps.reduce(function(total, ts) {
return total + toSeconds(ts);
}, 0);
const result = secondsToHHMMSS(totalSeconds);
console.log(result);
If you want to sum of times then you should try this
var addTime = function (time1, time2) {
// convert to ms
var dateObject1 = new Date(time1).valueOf();
var dateObject2 = new Date(time2).valueOf();
return dateObject1 + dateObject2;
}
var time1 = new Date().setHours(4, 32, 5, 0);
var time2 = new Date().setHours(3, 14, 3, 0);
var sum = new Date(addTime(time1, time2));
var getFormatedTime = function (time) {
return time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()
}
console.log(getFormatedTime(sum))
The first thing you should look into is using an Array, since you have a number of objects of the same kind.
You should ideally have something like,
const times = ["04:32:05", "03:14:03", ...]
Once you have that, this problem reduces to a classic use-case for the reduce function.
The reduce function operates on an array and accumulates the value of the operation every step to yield one value at the end.
Here's an example solution for your problem
const times = ["04:32:05", "03:14:03"]
//const times = ["01:00:01", "01:00:10","01:54:00","01:30:00"]
let finalSum = times.reduce((sum, curr) => {
//Obtain the current timestamp as an array of numbers
//[HRS, MINS, SECS]
let currTimeStamp = curr.split(":").map(token => parseInt(token));
//Add the current seconds to the total seconds so far
sum[2] += currTimeStamp[2];
//See how many minutes you got leftover as a result of that addition
const leftOverMins = Math.floor(sum[2] / 60);
//Mod by 60, to keep the seconds under 60
sum[2] %= 60;
//Add the leftover minutes to the sum operation for minutes
sum[1] += (currTimeStamp[1] + leftOverMins);
//Similar procedure as above
const leftOverHours = Math.floor(sum[1] / 60);
sum[1] %= 60;
sum[0] += (currTimeStamp[0] + leftOverHours);
sum[0] %= 24;
return sum
}, [0, 0, 0])
console.log(finalSum.join(":"))
Hello hope this answer will help you, I recommand to replace your bottom part (where you calculate) I do pretty much the same thing, but in the good order and with round to avoid decimals problems
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
var allTimes = [splitTime1, splitTime2, splitTime3, splitTime4, splitTime5, splitTime6, splitTime7]
allTimes.forEach(element => {
hour += parseInt(element[0])
minute += parseInt(element[1])
second += parseInt(element[2])
})
minute += Math.round(second / 60);
second = second % 60;
hour += Math.round(minute / 60);
minute = minute % 60
console.log(hour+ ":" + minute + ":"+ second)
I have time (string) in this format: 01:01:01:01 (hours/minutes/seconds/milliseconds).
And I need to parse this time to milliseconds (number), how I can do this?
Use the following code ........
var string = "01:01:01:01";
var string_array = string.split(":");
var hours = string_array[0];
var mins = string_array[1];
var seconds = string_array[2];
var miliseconds = string_array[3];
var total_miliseconds = (hours*60*60*1000) + (mins*60*1000) + (seconds*1000) + (miliseconds);
console.log ("Total Miliseconds: " + total_miliseconds);
You can use something like this:
function toMilisecond(time) {
[hours, mins, seconds, miliseconds] = time.split(":");
return hours * 3600000 + mins * 60000 + seconds * 1000 + Number(miliseconds);
}
console.log(toMilisecond("01:01:01:01"));
I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.
I can't find correct search key for googling what I need.
Anyone know what should I search on google ? or someone knows some function about that?
PS. Mysql or Javascript
Try with date object in javascript
Like this
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:49")
var diff = Math.abs(d1-d2); // difference in milliseconds
Then convert the milliseconds to hours
var hours = parseInt((diff/(1000*60*60))%24);
You can go through it
Get the time difference between two datetimes
But the query is not clear do you want only the hour difference or you want the difference converted to hour format
Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?
here a code example of how to do it
var date1 = new Date("2017-07-25 09:30:49");
var date2 = new Date("2017-07-25 10:30:00");
var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();
console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateArray2= reggie.exec(dateString2);
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1); // difference in milliseconds
var hours = parseInt((diff/(1000*60*60))%24);
Try with the below dateFormatter function :
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:00")
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);
function dateFormatter(t){
var cd = 24 * 60 * 60 * 1000;
var ch = 60 * 60 * 1000;
var cm = 60*1000;
var d = Math.floor(t / cd);
var h = '0' + Math.floor( (t - d * cd) / ch);
var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}
I'm having problems changing a timecode into frames using JavaScript.
running at 30 fps we get
"00:00:01:00" = 30 frames
So far so good, only I check the number of seconds at it gets converted to this:
Firstly Not sure what's going on there?!
It's been pointed out that I had \f instead of \nf.
Secondly
The frames returned is incorrect.
1 minute should be 1800 seconds not 1800000
Bonus points if you can tell me if that's an Ankh or not.
// set the frame rate or Frame Rat as we like to call him
var frameRat = 30 // fps
var numOfFrames = 60 // animation frame count
var animTime = "00:01:00:00" // time code
var a = convertTimeToFrames(animTime, frameRat);
var result = animTime + " at " + frameRat + " fps\n = " + a + " frames.";
alert(result);
function convertTimeCodeToSeconds(timeString, framerate)
{
var timeArray = timeString.split(":");
var hours = timeArray[0] * 60 * 60;
var minutes = timeArray[1] * 60;
var seconds = timeArray[2];
var frames = timeArray[3]*(1/framerate);
var str = "h:" + hours + "\nm:" + minutes + "\ns:" + seconds + "\f:" + frames;
alert(str)
var totalTime = hours + minutes + seconds + frames;
//alert(timeString + " = " + totalTime)
return totalTime;
}
function convertTimeToFrames(timeString, framerate)
{
var secs = convertTimeCodeToSeconds(timeString, framerate);
return secs * framerate;
}
You are doing operations between numbers and chars. Convert all values to Numbers after the split as follows:
// set the frame rate or Frame Rat as we like to call him
var frameRat = 30 // fps
var numOfFrames = 60 // animation frame count
var animTime = "00:01:00:00" // time code
var a = convertTimeToFrames(animTime, frameRat);
var result = animTime + " at " + frameRat + " fps\n = " + a + " frames.";
alert(result);
function convertTimeCodeToSeconds(timeString, framerate)
{
var timeArray = timeString.split(":");
var hours = parseInt(timeArray[0]) * 60 * 60;
var minutes = parseInt(timeArray[1]) * 60;
var seconds = parseInt(timeArray[2]);
var frames = parseInt(timeArray[3])*(1/framerate);
var str = "h:" + hours + "\nm:" + minutes + "\ns:" + seconds + "\nf:" + frames;
alert(str)
var totalTime = hours + minutes + seconds + frames;
//alert(timeString + " = " + totalTime)
return totalTime;
}
function convertTimeToFrames(timeString, framerate)
{
var secs = convertTimeCodeToSeconds(timeString, framerate);
return secs * framerate;
}
I have requirement to converting integer value to time format using javascript.
My requirement is that the result should be in time format.
Example 08:55 and 09:55
If I add these two as numbers then I will get 18.10 but I need 18:50
Try this: (My solution assumes the sum of times is not more than 24 hours)
function pad(str) {
return ("00"+str).slice(-2);
}
var str1 = "08:55";
var str2 = "09:55";
var token1 = str1.split(":");
var token2 = str2.split(":");
var result = token1[0] * 60 + + token1[1] + + token2[0] * 60 + + token2[1];
var newTime = pad(Math.floor(result/60)) + ":" + pad(result % 60);
console.log(newTime);