Convert hundredths to “minutes:seconds.hundredths” in javascript - javascript

In Javascript, I need help to convert an integer with hundredths to "minutes:seconds.hundredths".
So for example, I have this: '10420' and want to display it like this: 01:44.20.
Any Ideas?

function leading0(number){ return number < 10 ? "0" : "";}
mins = parseInt((hundredths / 100) / 60)
secs = parseInt((hundredths / 100) % 60)
huns = parseInt(hundredths % 100)
output = leading0(mins) + mins + ":" + leading0(secs) + secs + "." + leading0(huns) + huns;
jsFiddle example: http://jsfiddle.net/cNu2t/

var hundredths = 10420;
var seconds = Math.floor(hundredths / 100);
var minutes = Math.floor(seconds / 60);
return minutes+":"+(seconds-minutes*60)+"."+("0"+(hundredths-seconds*100)).substr(-2);
or:
function leadingZero(n) { return ("00"+n).substr(-2); }
var hundredths = 10420;
var secs = ~~(hundreths/100);
var mins = ~~(secs/60);
return mins+":"+leadingZero(secs%60)+"."+leadingZero(hundredths%100);

Moment.js should be able to handle this based on it's pretty rich set of formatting, parsing, etc. that it offers. I don't know if you'll be doing enough additional date and/or time related stuff to make adding a 5K JavaScript library to the set of resources you download for a page, but it might be worth a look if you have other spots where you could put it to use.
I know it deals in milliseconds and you can just multiply your number by ten to get to milliseconds and then pass it through their formatting function to output what you're after I think.

Related

Converting to duration from milliseconds

I am trying to convert time duration from the format of mm:ss.mss to entirely milliseconds and back.
I've already have a working function for converting from milliseconds to duration but I cannot seem to get it the other way around.
Lets say for instance that I have the duration 32:29.060, I want to convert it to milliseconds. For that I use this function:
function millisecondsToTime(ms, digits) {
digits = digits || 12;
return new Date(ms).toISOString().slice(23-digits, -1);
}
var a = millisecondsToTime(5549060, 9);
but whenever I try to convert back to time duration, I fail. I've tried parsing individually the minutes, seconds and milliseconds but it doesn't seem to work.
Here is the code that I've used for it:
var firstSplit = a.split(':')
var minutes = firstSplit[0]; //1
var secondSplit = firstSplit[1].split('.');
var seconds = secondSplit[0]; //2
var millisec = secondSplit[1]; //3
var conversion = ((+minutes) * 60 + (+seconds) * 60 + (+millisec))*1000;
I have an input bar which takes the format of mm:ss.mss and I need to convert it to milliseconds. How can I do that?
you can just return a
new Date(ms)
to get a date from ms.
And to get the same date as ms,
date.getTime() // returns ms from date object
Full example:
const ms = 5549060
const date = new Date(ms) // get a date from ms
console.log(date.getTime) // logs 5569060
If your input is a string in the format of mm:ss.mss, and you want to get a date from it, you can use moment.
const moment = require('moment')
const date = moment('22:15.143', 'mm:ss.SSS') // get date from pre specified format
You can use the string methods indexOf() and substr() to get the individual numbers out of your string and calculate the time accordingly.
I'm afraid though your millisecondsToTime() function isn't working properly.
5549060 milliseconds are roughly 92 minutes and it's returning 32:29.060
function backToTime(time) {
var index = time.indexOf(":");
var minutes = time.substr(0, index);
var seconds = time.substr(index + 1, time.indexOf(".") - (index + 1));
var milliseconds = time.substr(time.indexOf(".") + 1, time.length);
return parseInt(minutes * 60 * 1000) + parseInt(seconds * 1000) + parseInt(milliseconds);
}
console.log(backToTime("32:29.060"));
Your conversion to milliseconds is not working, this is basic math approach to both conversions:
let input = 5549060
//toDuration
let seconds = Math.floor(input / 1000);
let ms = input - seconds*1000;
let m = Math.floor(seconds / 60);
let s = seconds - m*60;
duration = m + ":" + s + "." + ms
console.log(duration)
//toMilliseconds
let holder = duration.split(":");
m = parseInt(holder[0]);
holder = holder[1].split(".");
s = parseInt(holder[0]);
ms = parseInt(holder[1]);
milliseconds = (m*60 + s)*1000 + ms
console.log(milliseconds)
If needed add check for ms length to add 0s, if you need it to have length of 3
I think your milliseconds to duration converter will be broken for durations above 60 minutes. This is because using Date the minutes field will wrap over into the minutes after 59 seconds have passed. If you want to get good support for values beyond 59 in your first field, I think maybe moving to a regex-based parser and using multiplication and addition, division and modulo to extract and reduce the fields manually might be nice. Something like this maybe:
var duration = ms => `${(ms / 60000) | 0}`.padStart(2, '0') + `:` + `${ms % 60000 / 1000 | 0}`.padStart(2, '0') + `.` + `${ms % 1000}`.padStart(3, '0')
var millisec = durat => (match => match && Number(match[1]) * 60000 + Number(match[2]) * 1000 + Number(match[3]))(/^([0-9]+)\:([0-5][0-9])\.([0-9]{3})$/.exec(durat))
You can see given the input 5549060, this function provides output 92:29.60, which is exactly 60 seconds greater than your own, and I believe to be correct. Maybe it's intentional for your usecase, but I can't imagine that being so desirable generally...

Converting Playback Time to a Formatted String Javascript

I have a timestamp pulled from a video that I want to convert into a user-friendly string in javascript.
let now = Player.getCurrentTime();
let minutes = Math.floor(now / 60.0);
let seconds = ((now / 60.0) - minutes) * 60;
console.log(minutes+":"+(seconds < 10 ? "0":"")+seconds);
The console.log statement using the conditional operator works really nicely for quick results. Are there any basic Javascript functions that will allow me to create a string using the input as the console.log above?
UPDATE:
Quick shoutout to MrPickles
for the prompt response. I ended up just doing it manually via a helper function. If anyone needs a quick timestamp formatting, here's a quick freebie:
function formatTime(timestamp) {
let minutes = Math.floor(timestamp / 60.0);
let seconds;
let rawSeconds = ((now / 60.0) - minutes) * 60;
if(rawSeconds < 10.0) {
if(rawSeconds < 1.0) {
seconds = rawSeconds.toPrecision(2);
} else {
seconds = rawSeconds.toPrecision(3);
}
} else {
seconds = rawSeconds.toPrecision(4);
}
let mString = minutes.toString();
let sString = seconds.toString();
let displayTime = mString+":"+(seconds < 10 ? "0":"")+sString;
return displayTime;
}
In short, no.
There are date/time modules you can get to help with this but most of the popular ones are big. If this is all you are doing with the date then I would keep what you have.
If you find you are doing a lot with dates and formatting then date-fns may be an options.

Having Trouble Creating A Timer To Count From a Given Time

I need for a clock to count from a specific time. e.g. Time is 20:08:00 and then to count from there. I have searched high and low for an answer and no one has specifically come up with an answer(that Ive seen). So my normal clock is like this.
<script type="text/javascript">
function clock()
{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
dispTime = hours + ":" + minutes + ":" + seconds;
var basicclock = document.getElementById('basicclock');
basicclock.innerHTML = dispTime;
setTimeout("clock()", 1000);
}
clock();
</script>
So all I need is the time to start at say 20:08:00 (or a variable of time). I am wondering if it better to use a timer to achieve a set time and to count from that???
Any help would be appreciated.
First: Please try to extensively search SO for answers before asking questions, many helpful responses can be found if you look. ;)
If you are trying to countdown to a certain time/date I would recommend the answer found HERE
All code credit goes to author's answer above.
HTML - for display
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
Script (keep formatting and just modify the 4th line down for your target date)
setInterval(function(){
// set whatever future date / time you want here, together with
// your timezone setting...
var future = new Date("Sep 20 2014 21:15:00 GMT+0200");
var now = new Date();
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
DEMO OF THE ABOVE CODE
I would also look at these are other interesting solutions found on this post here HERE

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.

How to convert milliseconds into a readable date Minutes:Seconds Format?

In JavaScript I have a variable Time in milliseconds.
I would like to know if there is any build-in function to convert efficiently this value to Minutes:Seconds format.
If not could you please point me out a utility function.
Example:
FROM
462000 milliseconds
TO
7:42
Just create a Date object and pass the milliseconds as a parameter.
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
Thanks guys for your support, at th end I came up with this solution. I hope it can helps others.
Use:
var videoDuration = convertMillisecondsToDigitalClock(18050200).clock; // CONVERT DATE TO DIGITAL FORMAT
// CONVERT MILLISECONDS TO DIGITAL CLOCK FORMAT
function convertMillisecondsToDigitalClock(ms) {
hours = Math.floor(ms / 3600000), // 1 Hour = 36000 Milliseconds
minutes = Math.floor((ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor(((ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
return {
hours : hours,
minutes : minutes,
seconds : seconds,
clock : hours + ":" + minutes + ":" + seconds
};
}
In case you already using Moment.js in your project, you can use the moment.duration function
You can use it like this
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
See jsbin sample
It's easy to make the conversion oneself:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
You may like pretty-ms npm package: https://www.npmjs.com/package/pretty-ms
If that what you are searching. Headless nice formatting (time in the units that are needed as ms grow), personalisable, and cover different situations. Small and efficient for what it cover.
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}

Categories