Does anyone how can I do a time difference count in Javascript?
Example:
If I have the following time (24H format)
startTime = 0615
endTime = 1530
breakTime = 0030
how can I get the following output?
diffB4Break = 7.15 hours
afterBreak = 6.45 hours
There are complications here, for example you would need to know what the maximum shift was, and whether it is possible for a worker to be scheduled to work over the threshold of a day, i.e. start work at 2300 and finish at 0900.
It very quickly becomes clear why it's better to use a Date/Time object to handle dates and time-deltas.
In Javascript have a look at Date
Based on #Guffa's answer here:
function parseTime(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
var startTime = '6:45';
var endTime = '15:30';
var diff = parseTime(endTime) - parseTime(startTime);
var min = diff % 60;
var hrs = parseInt(diff / 60);
alert(hrs + ":" + min);
Related
I have a string containing 13:00 , i have an duration of 90 for example and i have to convert the duration to hh:mm which i made it. Now i have a string with 1:30. How can i add this 1:30 string to the other 13:00 string so i can compare it with another strings? This is how i conver the duration
var bookH = Math.floor(data[0]['Duration'] / 60);
var bookM = data[0]['Duration'] % 60;
var bookingDurationToHour = bookH + ':' + bookM;
There is momentjs in the project but i still do not know how can i do that.
A solution with plain javascript.
var time = "13:00";
var totalInMinutes = (parseInt(time.split(":")[0]) * 60) + parseInt(time.split(":")[1]);
var otherMinutes = 90;
var grandTotal = otherMinutes + totalInMinutes;
//Now using your own code
var bookH = Math.floor(grandTotal / 60);
var bookM = grandTotal % 60;
var bookingDurationToHour = bookH + ':' + bookM;
alert(bookingDurationToHour);
Plunker
I've used Datejs before as vanilla JS with dates can be a bit difficult
First you want to put your time into a date time object
var myDate = Date.parse("2017-05-25 " + time);
Then you can add your time using the Datejs library:
myDate = myDate.addMinutes(90);
Then toString your new date as a time:
var newTime = myDate.toString("HH:MM");
I have seen many posts about decimal hours to hours:minutes, but I have not found any that work for more than a days worth.
I am using the following with moment.js..
function formatHours(decimalHours) {
var duration = moment.duration(decimalHours, 'hours');
var hours = duration.hours();
var minutes = duration.minutes();
var date = moment().hours(hours).minutes(minutes);
var result = date.format('HH:mm');
return result;
}
but this does not work for greater than 24 hours,eg I have a hours coming in representing over a year.
Is there a ways to handle this, and also format for the current locale (as moment should do)
Thanks in advance for any help
I have no idea what Moment.js is and I am not sure what you are trying to achieve exactly. However, if I understand it well, you want to be able to convert decimal hours, going as high as you want, into a date.
I can propose you this code:
function formatHours(decimalHours) {
let minutes = decimalHours % 1;
let hours = decimalHours - minutes;
minutes *= 60;
minutes = Math.round(minutes);
if (hours > 24) {
var day = Math.floor(hours / 24);
hours %= 24;
}
let date = new Date();
date.setHours(hours);
date.setMinutes(minutes);
if (day) {
date.setDate(day);
}
console.log(`${date}`);
}
formatHours(24.88);
This will handle any decimal input up to 672.00 (28*24), you can just improve it to handle month and so on.
As commenter asked, what format are you looking for?
I would recommend adding moment-duration-format plugin which seems to be written just for your usecase. Then you could simply write:
function formatHours (decimalHours) {
return moment.duration.format(hoursDecimal, 'hours').format('D:HH:mm');
};
// This is for moment.js in angular
list : any = ["9:12","4:35","9:11"]; // declare properly
for(var i=0 ; i < 3; i++){
var parts = this.list[i].split(":");;
var hours = parseInt(parts[0]) ;
var minutes = parseInt(parts[1]);
this.a = moment.duration(this.a._data.hours,'hours').add(hours,'hours').add(this.a._data.minutes,'minutes').add(minutes,'minutes');
}
var totalHours = (24 * this.a._data.days) + this.a._data.hours ;
var total = totalHours + ":" +this.a._data.minutes;
}
I currently have an Asp.net MVC 4 application with a screen for Time entry. On this screen I use some various Kendo controls and Razor Html helpers for example:
#(Html.Kendo().TimePickerFor(m => m.StartTime).Name("startTime"))
I have the samething for endTime as well. Right now I have some Javascript that correctly handles my desired outcome, although the rounding could be better, but it is messy and I'm sure there is a better way to handle it. That code looks something like this:
function change() {
var startTime = $("#startTime").val()
var endTime = $("#endTime").val()
var start = "01/01/2015 " + startTime
var end = "01/01/2015 " + endTime
var timeDiff = Math.abs(new Date(end) - new Date(start));
var d = timeDiff / 1000 / 60 / 60
var diffM = d * 2
var diffR = Math.ceil(diffM)
var diff = diffR / 2
$('#HoursWorked').val(diff)
$('#TotalBillTime').val(diff)
}
The outcome I want is the EndTime to be Subtracted from the StartTime, and the difference to be converted and rounded to be displayed as an HoursWorked count in hours. Right now it does hours and half hours. Is there a way to avoid all of this extra code? Also mathematically is there a way to round this more precisely or to include hours, half hours, and quarter hours?
I apologize if this is a bad question I am newer to Javascript and not familiar with many additional libraries or objects.
Check out Moment.js
function change() {
var startTime = $("#startTime").val()
var endTime = $("#endTime").val()
var start = "01/01/2015 " + startTime
var end = "01/01/2015 " + endTime
var timeDiff = moment(end) - moment(start);
var diff = moment.duration(timeDiff).asHours();
$('#HoursWorked').val(diff)
$('#TotalBillTime').val(diff)
}
EDIT
Sorry, that didn't answer your question about representing the hours in full, half and quarter increments. For that you still need to employ some maths. The formula you need is:
Math.ceil(hours * 4) / 4
For example:
> Math.ceil(1.053 * 4) / 4
1.25
> Math.ceil(1.50001 * 4) / 4
1.75
> Math.ceil(1.4999 * 4) / 4
1.5
So going back to the example:
var diff = moment.duration(timeDiff).asHours();
var roundedDiff = Math.ceil(diff * 4) / 4;
First off, JavaScript's date functions are severely lacking. It's absurd.
Second, there is several cool frameworks to make it better.
Countdown allows you to represent the diff between two dates easily.
http://countdownjs.org/
Moment.js makes overall date handling SO much better.
http://momentjs.com/
Ok on My dev machine I have the following code:
JScript
setInterval(function () { myTimer(); }, 1000);
function myTimer() {
var d = new Date();
var hrs = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var dayOfWeek = d.getDay();
// Let's do this logically.
// To get the number of victims so far today we need to know how many seconds have passed so far today.
var totalSeconds = sec + (min * 60) + (hrs * 3600); // Number of Seconds passed so far today.
// Now multiply that by 14 in accordance with Symantec's research.
var VictimsToday = totalSeconds * 14;
// To get the number of victims this week we need to multiply
// The number of seconds in a day by the number of full days and add the number of seconds of this partial day.
var TotalSecondsInADay = 86400; // According to Google.
var DaysSoFarThisWeek = dayOfWeek + 1; // Removes today as a partial day.
// We already know how many seconds are in this partial day = totalSeconds
// So our calculation is
var tsD = TotalSecondsInADay * DaysSoFarThisWeek;
var VictimsThisWeek = (totalSeconds + tsD) * 14;
// Now we get the Day of the Year remove today as a partial day and calculate
// Number of seconds a day by the number of complete days so far + todays partial day
var DOY = DayOfYear();
var tsY = DOY * totalSeconds;
var VictimsThisYear = (totalSeconds + tsY) * 14;
document.getElementById("FooterStatistics").innerHTML = Intl.NumberFormat().format(VictimsToday);
document.getElementById("FooterStatistics2").innerHTML = Intl.NumberFormat().format(VictimsThisWeek);
document.getElementById("FooterStatistics4").innerHTML = Intl.NumberFormat().format(VictimsThisYear);
}
function DayOfYear() {
var today = new Date();
var first = new Date(today.getFullYear(), 0, 1);
var theDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + 0.5, 0);
return theDay;
}
With the HTML being:
BODY
<div id="FooterStatistics"></div>
<div id="FooterStatistics2"></div>
<div id="FooterStatistics4"></div>
Now on the Dev machine the calculation returned in the DIV is:
However, when I run this on W3Schools Tryit Editor: http://www.w3schools.com/js/tryit.asp?filename=tryjs_date_getday
I get a totally different calculated result:
Now I know the numbers will be different because of TimeZone differences - what should not be different is the actual calculations. The Dev machine's second result is smaller than the first which it should NEVER be, and the third result is apparently not even a number - where upon the results in the TryIt editor provide more reasonable asnwers.
How can this be?
While creating apps, keep using console.log() to check the values. This really helps to understand what is happening, in the future. This is not an alternative to debugging, though, but it helps. You could only remove them when your code is to go live, or you are sure it works and is well abstracted.
PS: Avoid using w3schools.com. Use MDN. It's much better.
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.