Add 2 times together JavaScript - javascript

Looking to add time together within javascript.
I have never written any javascript, and as such am struggling with the way to progress.
I have got to add say 4:00 (4 hours) to 12:44 (Current Time) Is this possible within javascript?
The answer should report back 16:44
If so, how would I go about it?
Thanks

If you break it down into a couple of small helper functions, it's not too hard:
// Convert a time in hh:mm format to minutes
function timeToMins(time) {
var b = time.split(':');
return b[0]*60 + +b[1];
}
// Convert minutes to a time in format hh:mm
// Returned value is in range 00 to 24 hrs
function timeFromMins(mins) {
function z(n){return (n<10? '0':'') + n;}
var h = (mins/60 |0) % 24;
var m = mins % 60;
return z(h) + ':' + z(m);
}
// Add two times in hh:mm format
function addTimes(t0, t1) {
return timeFromMins(timeToMins(t0) + timeToMins(t1));
}
console.log(addTimes('12:13', '01:42')); // 13:55
console.log(addTimes('12:13', '13:42')); // 01:55
console.log(addTimes('02:43', '03:42')); // 06:25

Take a look at moment.js - an excellent library for managing all kinds of time related functionality - momentjs.com
Later addition to answer:
You mention your are a newbie with JavaScript so here is a simple working example of your problem using moment.js - this example assumes the file and moment.js are in the same folder. Check out the docs on the moment.js for all the formatting options. Good luck.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Time</title>
<script src="moment.js"></script>
</head>
<body>
<script>
//add 4 hours to the stated time
var theFutureTime = moment().hour('12').minute('44').add(4,'hours').format("HH:mm");
console.log(theFutureTime); // prints 16:44
</script>
</body>

Using moment.js you can convert hh:mm to minutes and add them.
Example:
moment.duration("02:45").asMinutes() + moment.duration("02:15").asMinutes()
Result: 300 mins
So, you can convert minutes to hh:mm:
function timeConvert1(data) {
var minutes = data % 60;
var hours = (data โ€“ minutes) / 60;
return (hours + โ€œ:โ€ + minutes);
}

For add array of time-format strings (including seconds and without counting days).
For example:
Input:
times = ['00:00:10', '00:24:00']
Output
00:24:10
// Add two times in hh:mm:ss format
function addTimes(times = []) {
const z = (n) => (n < 10 ? '0' : '') + n;
let hour = 0
let minute = 0
let second = 0
for (const time of times) {
const splited = time.split(':');
hour += parseInt(splited[0]);
minute += parseInt(splited[1])
second += parseInt(splited[2])
}
const seconds = second % 60
const minutes = parseInt(minute % 60) + parseInt(second / 60)
const hours = hour + parseInt(minute / 60)
return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}

function addHours(start, end) {
var mins= moment.duration(start).asMinutes() + moment.duration(end).asMinutes();
function z(n){return (n<10? '0':'') + n;}
var h = (mins/60 |0) % 24;
var m = mins % 60;
return z(h) + ':' + z(m);
}

Related

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}

Difference Between 2 Timestamps using javascript without using moment.js

I have 2 timestamps
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
I need the difference between these timestamps in hours and minutes using javascript but without using moment.js.
Means the output should in hours and minutes like for ex:(02h 13min).
Do provide some more context or in depth information of the solution you have up to now. That said, I understand the need/question of your second part "hours/minutes/seconds"; below is some context on that, or read up on it at milliseconds to time in javascript.
That being said,
You could just either try subtracting, as in end - start.. as in following code example.
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
document.write(endTimestamp - startTimestamp + '<br/>');
This will output 812041 - which are the milliseconds.
If you want to convert those milliseconds to the known format of hh:mm:ss.ms you can try the following code by example - also on jsfiddle.
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
document.write(endTimestamp - startTimestamp + '<br/>');
document.write(millisecondsToHoursMinutesSeconds(endTimestamp - startTimestamp));
document.write('<hr/>');
function millisecondsToHoursMinutesSeconds(ms) {
var milliseconds = parseInt((ms%1000)/100)
, seconds = parseInt((ms/1000)%60)
, minutes = parseInt((ms/(1000*60))%60)
, hours = parseInt((ms/(1000*60*60))%24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
Or read other solutions in this question: milliseconds to time in javascript

How to format time in JavaScript, without a framework [duplicate]

This is a common problem but I'm not sure how to solve it. The code below works fine.
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
const minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
const seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour ยท 60 seconds/minute) first, then calculate the remaining seconds:
const hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
Bonus:
Use the following code to pretty-print the time (suggested by Dru):
function str_pad_left(string, pad, length) {
return (new Array(length + 1).join(pad) + string).slice(-length);
}
const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);
Another fancy solution:
function fancyTimeFormat(duration) {
// Hours, minutes and seconds
const hrs = ~~(duration / 3600);
const mins = ~~((duration % 3600) / 60);
const secs = ~~duration % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
let ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
console.log(
fancyTimeFormat(1),
fancyTimeFormat(10),
fancyTimeFormat(100),
fancyTimeFormat(1000),
fancyTimeFormat(10000),
);
~~ is a shorthand for Math.floor, see this link for more info
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS :
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).
2020 UPDATE
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds to HH:MM:SS.
MATH:
Calculations use:
Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
The Math.floor() function returns the largest integer less than or equal to a given number.
% arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
LEADING ZEROS:
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
CODE:
function secondsToTime(e){
const h = Math.floor(e / 3600).toString().padStart(2,'0'),
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
s = Math.floor(e % 60).toString().padStart(2,'0');
return h + ':' + m + ':' + s;
//return `${h}:${m}:${s}`;
}
console.log(secondsToTime(7735)); // 02:08:55
/*
secondsToTime(SECONDS) // HH:MM:SS
secondsToTime(8) // 00:00:08
secondsToTime(68) // 00:01:08
secondsToTime(1768) // 00:29:28
secondsToTime(3600) // 01:00:00
secondsToTime(5296) // 01:28:16
secondsToTime(7735) // 02:08:55
secondsToTime(45296) // 12:34:56
secondsToTime(145296) // 40:21:36
secondsToTime(1145296) // 318:08:16
*/
2019 best variant
Format hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
You can also use native Date object:
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
Of course this solution works only for timeInSeconds less than 24 hours ;)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
To add leading zeros, I would just do:
const secondsToMinSecPadded = time => {
const minutes = "0" + Math.floor(time / 60);
const seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
};
console.log(secondsToMinSecPadded(241));
Nice and short
Moment.js
If you are using Moment.js then you can use there built in Duration object
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
Clean one liner using ES6
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
The most concise method I found can be done using in just one line:
let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`
Explanation
`${...}`Template literals. Allows for expressions to be converted into a string from within the string itself.Note: Incompatible with IE.
timeInSeconds/60|0Takes the seconds and converts in into minutes (/60). This gives a rational number. From here it is truncated using the bitwise OR (|0)
timeInSeconds%60Remainder (modulo). Gives the remainder of the variable divided by 60.
Hours
This method can be expanded to include hours like this:
let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`
Repeating this process, you can even include days.
A one liner (doesnt work with hours):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
Seconds to h:mm:ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
The Following function will help you to get Days , Hours , Minutes , seconds
toDDHHMMSS(inputSeconds){
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0){
ddhhmmss += Days + ' Day ';
}
if (Hour > 0){
ddhhmmss += Hour + ' Hour ';
}
if (Minutes > 0){
ddhhmmss += Minutes + ' Minutes ';
}
if (Seconds > 0){
ddhhmmss += Seconds + ' Seconds ';
}
return ddhhmmss;
}
alert( toDDHHMMSS(2000));
After all this, yet another simple solution:
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* #param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
Try this:
Converting Second to HOURS, MIN and SEC.
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
1 - Get rest of division using %. Now you have the seconds that don't complete a minute
2 - Subtract the seconds obtained in step 1 from the total. Now you have the minutes
For example, let's assume you have 700 seconds:
seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40
I was thinking of a faster way to get this done and this is what i came up with
var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}
If we want to convert "time" to minutes and seconds, for example:
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
Put my two cents in :
function convertSecondsToMinutesAndSeconds(seconds){
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
}
So this :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
Will have the following output :
[1,41];
Then you can print it like so :
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
export function TrainingTime(props) {
const {train_time } = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `${hours} hrs ${minutes} min ${seconds} sec`;
}
Day.js
If you use day.js, try this.
const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
const time = dayjs.duration(100, 'seconds')
time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40
I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:
function format(n) {
let mil_s = String(n % 1000).padStart(3, '0');
n = Math.trunc(n / 1000);
let sec_s = String(n % 60).padStart(2, '0');
n = Math.trunc(n / 60);
return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}
console.log(format(241));
https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart
Here's an ES6 version of the seconds to minutes and seconds conversion, with padding (00:00 format). It only accepts integer values for seconds and ~~(x) is the shorthand floor operation.
const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
`${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;
for (let i = 0; i < 10; i++) {
const seconds = ~~(Math.random() * 300);
console.log(seconds, secondsToMinSec(seconds));
}
if you need to work with the result easily later this is what I use:
function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}
}
(used Vishal's code)
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
You've done enough code to track minutes and seconds portions of time.
What you could do is add the hours factor in:
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60

Javascript time difference via timepicker

I'm working on a web timesheet where users use timepicker to determine start & end times and I'd like to have the form automatically find the difference between the two times and place it in a 3rd input box. I understand that I need to get the values, convert them to milliseconds, then subtract the first number from the second, convert the difference back to human time and display that in the third box. But I can't seem to wrap my head around time conversion in javascript. Here's what I have so far:
function date1math(){
var date1in = document.getElementById("date-1-in").value;
var date1out = document.getElementById("date-1-out").value;
date1in = date1in.split(":");
date1out = date1out.split(":");
var date1inDate = new Date(0, 0, 0, date1in[0], date1in[1], 0);
var date1outDate = new Date(0, 0, 0, date1out[0], date1out[1], 0);
var date1math = date1outDate.getTime() - date1inDate.getTime();
var hours = Math.floor(date1math / 1000 / 60 / 60);
date1math -= hours * 1000 * 60 * 60;
var minutes = Math.floor(date1math / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
document.getElementById("date-1-subtotal").value = date1math(date1in, date1out);
}
I want to take the timepicker result (say 9:00am) from the input date-1-in, the timepicker result (say 5:00pm) from the input date-1-out, and then place the difference as a number in date-1-subtotal.
Presumably the input is a string in the format hh:mm (e.g. 09:54) and that the two strings represent a time on the same day. You don't mention whether an am/pm suffix is included, but it's there in the text so I'll assume it might be.
If daylight saving changes can be ignored, the simplest method is to convert the string to minutes, find the difference, then convert back to hours and minutes, e.g.:
// Convert hh:mm[am/pm] to minutes
function timeStringToMins(s) {
s = s.split(':');
s[0] = /m$/i.test(s[1]) && s[0] == 12? 0 : s[0];
return s[0]*60 + parseInt(s[1]) + (/pm$/i.test(s[1])? 720 : 0);
}
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function getTimeDifference(t0, t1) {
// Small helper function to padd single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var diff = timeStringToMins(t1) - timeStringToMins(t0);
// Format difference as hh:mm and return
return z(diff/60 | 0) + ':' + z(diff % 60);
}
var t0 = '09:15am';
var t1 = '05:00pm';
console.log(getTimeDifference('09:15am', '05:00pm')); // 07:45
console.log(getTimeDifference('09:15', '17:00')); // 07:45
If daylight saving is to be incorporated, you'll need to include the date so that date objects can be created and used for the time difference. The above can use either 12 or 24 hr time format.

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