I am using the following code to get difference between two dates in hrs, minutes and seconds, which I will save later in database as a string field. So I was wondering if it is possible to use Moment.js library or any Javascript functionally in order to get the total number of hours, minutes and seconds for all date differences saved in the database (ex. 02:24:33 + 03:12:20 + 12:33:33) as one final HH:MM:SS taking in consideration that the HH could exceed 24 if the total number of hours summed exceeded 24? Thanks
$('.set-start-time').on("dp.change",function (e) {
$('.set-end-time').data("DateTimePicker").setMinDate(e.date);
});
$('.set-end-time').on("dp.change",function (e) {
$('.set-start-time').data("DateTimePicker").setMaxDate(e.date);
var now = $('.set-start-time').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-time').data('DateTimePicker').getDate().toLocaleString();
console.log(moment.utc(moment(then,"DD/MM/YYYY HH:mm:ss").diff(moment(now,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"));
//Output here come in format ex. 02:42:33
});
It's probably too late for this to matter, but maybe something like this would help:
http://jsfiddle.net/8s8v3evf/8/
tl;dr
once you have your diff:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function diffAsString(diff_ms) {
var hours = Math.floor(diff_ms / 3600000);
diff_ms -= (hours * 3600000);
var minutes = Math.floor(diff_ms / 60000);
diff_ms -= (minutes * 60000);
var seconds = Math.floor(diff_ms / 1000);
return zeroPad(hours, 2) + ':' + zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);
}
Related
I am currently working with hours as numbers, such as 2230 being equivalent to 22:30. I would like to be able to add numbers to it and sum as if they were minutes added to hours
2030 + 60 = 2130 //and not 2090
2330 + 120 = 0230 //and not 2350
Is there a library or function to doing this? Or perhaps I should change the way I am handling hours?
I don't recommend doing this, but if you want to do it, you have to handle the fact that you're pretending an hour is 100 minutes. You do that by extracting the real hours and minutes from the fake value, doing the math on them, and then reassembling them, something along these lines:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
const hours = ahours + bhours + Math.floor((aminutes + bminutes) / 60);
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
Live Example:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
// The % 24 wraps around
const hours = (ahours + bhours + Math.floor((aminutes + bminutes) / 60)) % 24;
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
console.log(add(2030, 60));
console.log(add(2330, 120));
But again, I don't recommend this. Instead, work with time values (Date or just milliseconds-since-the-Epoch, etc.) and convert for display when you need to display it.
Note that 50 rather than 0250, for two reasons: 1. 2330 + 120 is 2450 which is 00:50, not 02:50, and numbers don't have leading spaces except in string representations.
Here's my implementation of it
function add(current, time) {
const hours = Math.floor(time / 60);
const minutes = time % 60;
const currentMinutes = parseInt(current.toString().slice(2));
const currentHours = parseInt(current.toString().slice(0, 2));
const newMinutes = (currentMinutes + minutes) % 60;
const additionalHours = (currentMinutes + minutes) > 60 ? 1 : 0;
const newHours = (currentHours + hours + additionalHours) % 24;
return `${newHours < 10 ? '0' : ''}${newHours}${newMinutes < 10 ? '0' : ''}${newMinutes}`;
}
console.log(add(2030, 60)); // 2130
console.log(add(2330, 120)); // 0130
here is the working code for your clock.
var nowTime = '2350'; //current time in String..
var newMin = 120; // min you want to add in int..
var tMinutes = parseInt(nowTime.toString().slice(2)); //taking out the min
var tHours = parseInt(nowTime.toString().slice(0, 2)); //taking out the hr
var newMinutes = (newMin + tMinutes) % 60;
var newHr = tHours + parseInt(((newMin + tMinutes) / 60));
var newTime = `${newHr >= 24 ? newHr-24 : newHr}${newMinutes}`;
newTime = newTime.length < 4 ? '0'+newTime : newTime;
console.log(newTime);
If you want to handle date math, a library is probably best, because date math is hard, and the source of so many bugs if done wrong. Now, knowing how to do date math is a great thing to learn though, and reading through the source code of date math libraries is a good way to do that. Luxon is a good library with duration objects that can do what you need easily, and has readable source code. Other duration libraries also exist, so take a look at a few of those and see what you like the best. You can also abuse he built-in Date library to act like a duration object, but I don't think that's worth it.
But libraries aside, let's analyze the problem and what you might want to consider in solving it.
First off, I would say your first problem is trying to use a data type that isn't designed for what you want. A single integer is not a good idea for representing two values with different units. That is sort of what T.J. meant when he said it's a presentation concept. You have one object, but it's not really an integer in behavior. And date is close, but not quite right. So let's make a class. Duration seems like a good name:
class Duration { … }
We know it has two parts, hours and minutes. Also, it seems a good idea to just use one unit and convert them. (You wouldn't have to, but it actually makes the math easier if you do the conversion):
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
}
Now lets make some getters to get just the minutes section and the hours section:
class Duration {
…
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
}
Now we need to add them together. Some languages would let you use + for this, but javascript has limits on what we can make + do, so we'll add our own method. Note that because of how our constructor works, we can have more than 60 minutes when we initialize the values. Is this a good idea? Maybe. Depends on how you want the object to behave. (While we'll go with it for this example, there are definite arguments against it, mostly because it is a bit confusing that get minutes doesn't return over 60 - but it's also makes a certain sense at the same time).
class Duration {
…
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
And now we can add our duration objects together, and the math is taken care of for us.
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
d1 = new Duration({hours:20, minutes: 30})
d2 = new Duration({minutes: 50})
console.log(d1.asDisplayString(), '+', d2.asDisplayString(), '=', d1.add(d2).asDisplayString())
I need to split time (hh:mm:ss) by an integer. For example 13:14:24 / 12.
If I convert it into date and divide:
new Date( date.getMonth()+1 + " " +
date.getDate() + ", " +
date.getFullYear() + " " +
"13:14:24") / 12;
I get a really long number 119579922000, is it date / 12 in milliseconds? I need the result to be in the same hh:mm:ss format.
var h = 13, m = 14, s = 24;
var secsSinceMidnight = (h*3600) + (m*60) + s;
var oneTwelth = secsSinceMidnight / 12;
h = Math.floor(oneTwelth / 3600);
m = Math.floor( (oneTwelth % 3600) / 60);
s = Math.floor( (oneTwelth % 3600) % 60);
console.log(h + ":" + m + ":" + s);
Here is an alternative approach using the Sugar.js library, which is my personal choice extension for date handling in JavaScript:
var midnight = Date.create().beginningOfDay();
var secsSinceMidnight = Date.create().secondsSince(midnight);
console.log( (secsSinceMidnight/12).secondsAfter(midnight) );
To explain the last line: secondsAfter is a function defined on the Number type. It is returning a Date object, which is then sent to console.log().
Just another plain-old-javascript alternative, but done in one line of code.
return (new Date((date - date.getTimezoneOffset() * 60000) % 86400000 / divisor )).toUTCString().split(' ')[4];
It adjusts by timezone (minutes) as the math is in UTC. Next divides the modulo (86400000 milliseconds = 1 day) by a divisor. Returns a formatted time string.
Working Example:
function getTimeSlice( date, divisor ) {
return (new Date((date - date.getTimezoneOffset() * 60000) % 86400000 / divisor )).toUTCString().split(' ')[4];
}
// Test
var test = new Date( );
test.setHours(13, 14, 24, 0);
stdout.innerHTML = getTimeSlice( test, 12);
<div id="stdout"></div>
Not quite sure what you're trying to do, but it might help to have a couple of simple functions, one to convert h:m:s to seconds, and one to convert seconds to h:m:s.
E.g.
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
// Convert seconds to hh:mm:ss
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60 |0);
}
So if you want to divide a time by 12, then:
console.log(secondsToHMS(hmsToSeconds('13:14:24')/12)); // 01:06:12
I am trying to write a code that can do the following :
Calculates time difference (in HH:MM format) between two type="time" elements on a row.
Sum the total difference (in HH:MM format) in text input.
I've managed to create a function fired by the onchange event, but my function is only considering the first values entered, meaning that when you update the timings, the difference will be recalculated and the total will be wrong.
Here is my JavaScript code for calculating the first line:
function CalTime0() {
var timeOfCall = $('#timefrom0').val(),
timeOfResponse = $('#timeto0').val(),
hours = timeOfResponse.split(':')[0] - timeOfCall.split(':')[0],
minutes = timeOfResponse.split(':')[1] - timeOfCall.split(':')[1],
total = $('#tbtotal').val(),
tothours = total.split(':')[0],
totminutes = total.split(':')[1];
minutes = minutes.toString().length<2?'0'+minutes:minutes;
totminutes = totminutes.toString().length<2?'0'+totminutes:totminutes;
if(minutes<0) {
hours--;
minutes = 60 + minutes;
}
hours = hours.toString().length<2?'0'+hours:hours;
tothours = tothours.toString().length<2?'0'+tothours:tothours;
tothours = parseInt(tothours) + parseInt(hours);
totminutes = parseInt(totminutes) + parseInt(minutes);
if(totminutes >= 60) {
tothours++;
totminutes = totminutes - 60;
}
$('#total0').val(hours + ':' + minutes);
$('#tbtotal').val(tothours + ':' + totminutes);
}
The solution is to substract the time the #total0 field represents from the time the #tbtotal field represents. Then you calculate the new #total0 field, and add that time to #tbtotal again. This way the time displayed in #tbtotal is always correct.
The other question seemed to be how to do this for all rows, instead of just this one. You can use the this keyword to figure out what element fired the change event. From there you can figure out what the other elements would be. For this purpose I renamed the fields to timefr0 and timeto0, so they are equal length.
I took the liberty to convert all times to seconds, and manipulate them that way. The comments in the script should speak for themselfs.
function updateTotals() {
//Get num part of the id from current set
//Cheated a bit with the id names ;-)
var num = $(this).attr('id').substr( 6 );
//Get the time from each and every one of them
var tfrom = $('#timefr' + num ).val().split(':');
var tto = $('#timeto' + num ).val().split(':');
var currtotal = $('#total' + num ).val().split(':');
var grandtotal = $('#tbtotal').val().split(':');
//Convert to seconds and do the calculations the easy way
var diff = (tto[0] - tfrom[0]) * 3600 + (tto[1] - tfrom[1]) * 60;
var totalsec = currtotal[0] * 3600 + currtotal[1] * 60;
var grandtotalsec = grandtotal[0] * 3600 + grandtotal[1] * 60;
//If the result is negative, we can't do anything sensible. Use 0 instead.
if( diff < 0 ) {
diff = 0;
}
//Substract what we calculated last time
grandtotalsec -= totalsec;
//Then add the current diff
grandtotalsec += diff;
//Convert diff (or total) into human readable form
var hours = Math.floor( diff / 3600 );
diff = diff % 3600;
var minutes = Math.floor( diff / 60 );
hours = (hours < 10) ? "0" + hours.toString() : hours.toString();
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
//Convert grandtotal into human readable form
var grandtotalhours = Math.floor( grandtotalsec / 3600 );
grandtotalsec = grandtotalsec % 3600;
var grandtotalminutes = Math.floor( grandtotalsec / 60 );
grandtotalhours = (grandtotalhours < 10) ? "0" + grandtotalhours.toString() : grandtotalhours.toString();
grandtotalminutes = (grandtotalminutes < 10) ? "0" + grandtotalminutes.toString() : grandtotalminutes.toString();
//Put them in the fields
$( '#total' + num ).val( hours + ":" + minutes );
$( '#tbtotal' ).val( grandtotalhours + ":" + grandtotalminutes );
}
An example fiddle can be found here.
As a suggestion, to compute date differences more easily, use moment.js. The date difference computation should be replaceable by something like this, with moment:
moment(timeOfResponse).diff(moment(timeOfCall))
moment.js diff documentation: http://momentjs.com/docs/#/displaying/difference/
I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
You must understand what Date object represent and how it stores dates. Basically each Date is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
What you really need is:
var diffMillis = nu - tid1;
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
Working fiddle.
Having two strings (start and end time) in such form "16:30", "02:13" I want to compare them and check if the gap is greater than 5 mins.
How can this be achieved in Javascript in an easy way?
function parseTime(time) {
var timeArray = time.split(/:/);
// Using Jan 1st, 2010 as a "base date". Any other date should work.
return new Date(2010, 0, 1, +timeArray[0], +timeArray[1], 0);
}
var diff = Math.abs(parseTime("16:30").getTime() - parseTime("02:13").getTime());
if (diff > 5 * 60 * 1000) { // Difference is in milliseconds
alert("More that 5 mins.");
}
Do you need to wrap over midnight? Then this is more difficult. For example, 23:59 and 00:01 will produce a difference of 23 hours 58 minutes and not 2 minutes.
If that's the case you need to define your case more closely.
You can do as following:
if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}
// time is a string having format "hh:mm"
function Time(time) {
var args = time.split(":");
var hours = args[0], minutes = args[1];
this.milliseconds = ((hours * 3600) + (minutes * 60)) * 1000;
}
Time.prototype.valueOf = function() {
return this.milliseconds;
}
// converts the given minutes to milliseconds
Number.prototype.minutes = function() {
return this * (1000 * 60);
}
Subtracting the times forces the object to evaluate it's value by calling the valueOf method that returns the given time in milliseconds. The minutes method is another convenience method to convert the given number of minutes to milliseconds, so we can use that as a base for comparison throughout.
new Time('16:30') - new Time('16:24') > (5).minutes() // true
This includes checking whether midnight is between the two times (as per your example).
var startTime = "16:30", endTime = "02:13";
var parsedStartTime = Date.parse("2010/1/1 " + startTime),
parsedEndTime = Date.parse("2010/1/1 " + endTime);
// if end date is parsed as smaller than start date, parse as the next day,
// to pick up on running over midnight
if ( parsedEndTime < parsedStartTime ) ed = Date.parse("2010/1/2 " + endTime);
var differenceInMinutes = ((parsedEndTime - parsedStartTime) / 60 / 1000);
if ( differenceInMinutes > 5 ) {
alert("More than 5 mins.");
}