I'm writing code that will allow me to log my hours worked a little easier. I can get the minutes past a defined time to display but I can't seem to get the format on the output to be HH:mm, here's my code;
<html>
<head>
<title>Time Past Since 08:30</title>
<meta http-equiv="Refresh" content="60">
<script language="JavaScript">
var sd = new Date(); // Get system date (sd)
var sh = sd.getHours(); // Get system hour (sh)
var sm = sd.getMinutes(); // Get system minutes (sm)
wh = (08); // Specify work start hour (wh)
wm =(30); // Specify work start minute (wh)
var vctime = ((sh *60 + sm) - (wh *60 + wm)); // Get differnece for system and work start, this needs to display in hh:mm but isn't
document.write(vctime); // output
</script>
</head>
<body>
</body>
</html>
Since your result is in minutes, why not just use division to convert minutes elapsed into hours and then apply a modulus to extract the remaining minutes?
hours_since = Math.floor(vctime/60);
minutes_since = Math.round((vctime/60 % 1) * 60); // Use num % 1 to extract the decimal and convert it to minutes.
console.log(hours_since + ":" + minutes_since);
If you need the leading "0"s in your result, just write a simple conditional to check if the values are less than 10:
hours_zero_prefix = hours_since < 10 ? "0" : ""
minutes_zero_prefix = minutes_since < 10 ? "0" : ""
console.log(hours_zero_prefix + hours_since + ":" + minutes_zero_prefix + minutes_since);
I would suggest using diff in the Moment.js library to handle this calculation. The library will clean up the daylight saving time issues you would have by trying to do this by calculating the difference between the start and end hours. It looks like you want the difference in minutes between a start time and now. To do this with moment:
//returns number of minutes, accounting for DST based on the time zone of the local machine
var min = moment().diff(moment(yourStartDateTimeInIsoString), 'minutes');
//converts minutes to hours, then adds remaining minutes
return Math.floor(min/60) + ':' + min%60
Related
I've been going through the docs and I'm not sure what I'm doing wrong. I need to convert 7200 to 2:00:00. Seems easy? Some attempts:
var duration = 7200;
var display = moment().seconds(duration).format("h:mm:ss");
and...
var duration = 7200;
var display = moment.duration(duration, "seconds"); //can't chain on a format method?
The format comes back correct but the numbers are all wrong. If I use a duration of Math.round(7025.526) or 7025.526 I get 9:19:06 back.
How can I convert seconds to h:mm:ss successfully?
When you use moment().seconds(duration) it will take the current date and time, and then set the seconds component to the value (spilling over into minutes and hours). If you try it at different times you will see that the result changes.
A duration object can't be formatted as a date, because it's simply not a date. It's a length of time without any defined starting or ending point.
To convert the seconds first create an empty moment object, which will be the current date and the time 0:00:00. Then you can set the seconds, which will spill over into minutes and hours.
You would want to use H rather than h to format the hours. That avoids getting times less than an hour as 12:nn:nn instead of 0:nn:nn:
var duration = 7200;
var display = moment({}).seconds(duration).format("H:mm:ss");
let duration = seconds;
let hours = duration/3600;
duration = duration % (3600);
let min = parseInt(duration/60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) {
sec = `0${sec}`;
}
if (min < 10) {
min = `0${min}`;
}
if (parseInt(hours, 10) > 0) {
return (`${parseInt(hours, 10)} : ${min} : ${sec}`)
}
return (`${min} : ${sec}`)
You can do it manually by calculating hours minutes and seconds
Using the moment-duration-format plugin:
var s = moment.duration(ms).format("h:mm:ss");
Or, just using moment:
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
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);
}
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.
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.
I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);