how to convert milliseconds to minutes and milliseconds format - javascript

i'm receiving an audio track progress in milliseconds and need to convert it to minutes and milliseconds format M:MS, the format i'm aiming to achieve is similar to what we see in media player classic high precision option
i know the regular equation to format milliseconds to minutes and seconds which is like this:
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
but i don't know how to achieve the format i'm looking for. how can i do that? also how can i achieve the opposite?

For instance:
3.5 minutes == 210000ms
new Date(210000).toISOString().slice(14, -1) //03:30.000
or for tracks longer than an hour:
78 minutes == 4.68e+6ms
new Date(4.68e+6).toISOString().slice(12, -1) //1:18:00.000"
Is that what you were going for?

Related

Convert seconds to HH:MM:SS:MS and/or HH:MM:SS;F

I'm trying to write a logic to convert seconds to the following formats:
HH:MM:SS:MS, where MS is milliseconds
HH:MM:SS;F, where F are the frames
(and not just to HH:MM:SS, therefore this question is different from the others on Stackoverflow)
I have the following logic for getting the HH:MM:SS format currently:
getTime(seconds) {
let h = Math.floor(seconds / 3600);
seconds = seconds % 3600;
let min = Math.floor(seconds / 60);
seconds = Math.floor(seconds % 60);
if (seconds.toString().length < 2) seconds = "0" + seconds;
if (min.toString().length < 2) min = "0" + min;
return (h + ":" + min + ":" + seconds);
}
but how can I get milliseconds or frames?
If seconds is a float, you can take Math.round((seconds - Math.floor(seconds)) * 1000) to get remaining milliseconds. Or Math.round((seconds - Math.floor(seconds)) * fps) where fps is the number of frames per second.
If Your function only takes seconds, then there is no way to get milliseconds out of this information...
You can assume that it is zero milliseconds.
If you want to be accurate to milliseconds, your function should take milliseconds.
var getStringFromMS=(ms,res=[])=>(
[1000,60,60,24].reduce((rest,curr,i)=>(
res[3-i]=rest%curr,Math.floor(rest/curr)
),ms),res.join(":")
);
In action with current time
Simply iterate over the different periods and reduce the milliseconds to days, while doing that the result is stored in res, which can be joined then simply. You may replace 1000 with frames

Convert milliseconds to time in extjs or javascript

Is there a built in method in extjs or javascript for converting milliseconds to a time?
I found one for date, but it doesn't work. I always get Jan, 1 1970 08:00 (Pacific Standard Time). When I try test.getHours I get 0. I am trying to print out 8:00 or 08:00
var getSignOnRecord = 28800000;
var test = new Date(getSignOnRecord);
test.getHours() // 0 ???? Should be 8
you can use ISOString date formats for up to 24 hours of time:
new Date(28800000).toISOString().split("T")[1].split(".")[0]; // == "08:00:00"
you can easily slice() the remaining text to eliminate seconds or whatnot.
this works because using a "unix" stamp results in an GMT offset, and ISO also displays GMT, so by throwing away the date part, you're left with a pretty readable format of up to 23h59m59s...
You are getting the localized hour, but you want the hours at UTC
new Date(28800000).getUTCHours() // 8
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
The getHours() method returns the hour for the specified date, according to local time.
new Date(value);
value: Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC
28800000 ms is indeed 1 January 1970, 8h
When I try test.getHours I get 0
NB value is UTC, getHours is local time
This is a math problem. As far as I know, there is no function that does this in native JavaScript, but can be coded from scratch.
function convertToTime(milliseconds) {
var seconds = Math.floor(milliseconds / 1000) % 60
var minutes = Math.floor(milliseconds / (1000 * 60)) % 60
var hours = Math.floor(milliseconds / (1000 * 60 * 60)) % 24
return (hours < 10 ? "0" + hours : hours) + ":" +
(minutes < 10 ? "0" + minutes : minutes) + ":" +
(seconds < 10 ? "0" + seconds :seconds);
}
There's also probably a method like this in momentjs.

Vanilla JS - Displaying Video Length (if statement)

I am looking to display a video length in the following of two formats:
if less than 59 seconds:
{no_of_sec}
if above 59 seconds:
{no_of_sec} : {no_of_sec}
At the moment this code:
document.getElementById("video2").duration
Returns the following value:
18.133313
I only need need it roundest to the nearest second then in the format above. Without overthinking it, I presume I need to round it. This can be done using Math.round() but it is when the number goes above 59 seconds is where I am struggle.
I plan to put this into an function which would loop through video elements with a class called:
.has--videoDuration
Any ideas?
Given the number of total seconds, you can compute the minute / second components as shown in the snippet below:
var totalSeconds = 18.133313;
var minutes = Math.floor(totalSeconds / 60);
var seconds = Math.floor(totalSeconds % 60);
alert(minutes + ':' + seconds);
Building upon your code:
var duration = Math.round(document.getElementById("video2").duration);
var minutes = ~~(duration / 60); // 1 minute every 60 seconds
var seconds = duration - 60 * minutes; // Remaining seconds
var timeString = minutes ? (minutes + ':' + seconds) : seconds;
I guess the timeString is what you are looking for.
BTW: I would rather use Math.floor for the duration (or ~~), but the exact choice of duration normalization is independent of the rest.

How can I format time durations exactly using Moment.js?

I would like to do the following, given two dates in UTC formatting:
var start = "2014-01-13T06:00:00.0000000Z";
var end = "2014-01-13T14:16:04.0000000Z";
I would like to get the exact time span that passes between these two times, such as
8h 16m
I have tried using the following:
var duration = moment(moment(end) - moment(start)).format('hh[h] mm[m]');
But this does not work with days. Moreover, it does not work with days, since they are always >=1 even if <24 hours pass.
I have also tried twix.js to get the length, but its formatting doesn't support creating the format specified above, or I could not find the way to do so in its documentation. Basically I am looking for an exact version of twix.humanizeLength().
Moment.js's a.diff(b) provides only total durations, it can give me the length of the time span in minutes, hours or days, but not calculated using remainders.
My current solution is to use diff to create the ranges and then use modulo to calculate remainders, but this is not very elegant:
var days = moment(end).diff(start, 'days');
var hours = moment(end).diff(start, 'hours') % 24;
var minutes = moment(end).diff(start, 'minutes') % 60;
var duration = ((days > 0) ? days + 'd ' : '') + ((hours > 0) ? hours + 'h ' : '') + ((minutes > 0) ? minutes + 'm ' : '');
The question: Is there any smarter way to do this in either moment.js or twix.js, or should I take my time and develop my own moment.js plugin?
You can try using Durations, but I'm not sure if those have the capabilities you are looking for http://momentjs.com/docs/#/durations/
Also, you can always user moment's diff to get the difference in milliseconds and then format it to your needs. It is basically the same that you are doing, but you only call diff once.
function convertMilliSecondsIntoLegibleString(milliSecondsIn) {
var secsIn = milliSecondsIn / 1000;
var milliSecs = milliSecondsIn % 1000;
var hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ( hours + "h: "
+ minutes + "m: "
+ seconds +"s: " + milliSecs + "ms");
}
There's a plugin for formatting duration in moment.js : moment-duration-format
If it doesn't do what you need, then you should extend moment.duration.fn. If you don't support many locales, it should be easy enough.
In any case, I'd recommend to read the thread of this feature request.

JavaScript: clock and the Date()

So I have this clock script:
function digitalWatch(timestamp) {
var date = new Date(timestamp);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
document.getElementById("digital_watch").innerHTML = hours + ":" + minutes + ":" + seconds;
setTimeout(function(){digitalWatch(timestamp+1)}, 1000);
}
digitalWatch(<<here I pass a UNIX timestamp from server>>)
The clock don't work.
I debuged it with console.log() and I saw that timestamp incremented correctly but the Date() constructor returns the same result again and again.
Someone knows what's the problem here? And how can I solve it?
UNIX timestamps count in seconds, JavaScript timestamps count in milliseconds.
You should just multiply the passed timestamp by 1000, e.g.:
var date = new Date(timestamp * 1000);
This will not only fix the initial conversion, but ensure that when you add a second (in the timer callback) that you actually do add 1 second, and not just 1 millisecond. The latter is the reason that you appear to be getting the same Date object back - you're almost certainly not, but the new one is only 1ms later than the previous so will show the same HH:MM:SS value most of the time.
In practise, note that you'll find that setTimeout does not guarantee that the events will fire 1000ms apart so you will get some clock drift.
You ought to take into account how long the preceding code takes to run too - indeed a better approach may be to simply determine the difference between the originally supplied timestamp and the local computer's time, and use that as a reference value for all subsequent calls.

Categories