How to calculate the difference between time inputs in javascript? - javascript

I want to calculate my work time. It works fine when I input
08:00 - 09:00 = 01:00
But when I input this time
23:30 - 01:30 = 10:00
It should return 02:00
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
sMin -= 12 * 60;
diff = eMin - sMin
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">

I would use a Date object to calculate the difference in time. Since you are only interested in the time, you can use any date to construct a valid date string. The reason why you are getting 10 hours is because there is no date to show that it is 1am the following day (this is from my understanding of your question).
You can do something like below to get the job done.
const pad = num => (num < 10) ? `0${num}` : `${num}`;
const addADay = (start, end) => {
const sHour = parseInt(start.split(':')[0], 10);
const eHour = parseInt(end.split(':')[0], 10);
return (eHour < sHour);
};
const diffTime = (start, end) => {
const startDate = new Date(`2019/01/01 ${start}:00`);
const endDate = addADay(start, end)
? new Date(`2019/01/02 ${end}:00`)
: new Date(`2019/01/01 ${end}:00`);
const diff = endDate.getTime() - startDate.getTime();
const hours = Math.floor(diff / 3600000);
const min = (diff - (hours * 3600000)) / 60000;
return `${pad(hours)}:${pad(min)}`;
}
console.log(diffTime('08:00','09:00')); // returns 01:00
console.log(diffTime('23:00','01:30')); // returns 02:30

The most important part in the required algorithm is finding if the end date is tomorrow.
based on your code here is a working example with my suggestion.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button" onclick="diffTime()">CLICK
</button>
<input type="time" id="delay">
<script>
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime() {
var start = document.getElementById("timeOfCall").value;
var end = document.getElementById("timeOfResponse").value;
// start date will be today
var d1 = new Date();
var s = start.split(":")
var date1 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s[0],s[1],0,0);
var s2 = end.split(":")
// end date
if(s2[0] < s[0])
{
// its tommorow...
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
d1=tomorrow;
}
var date2 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s2[0],s2[1],0,0);
var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
alert(hh + ":" + mm + ":" + ss);
}
document.getElementById("timeOfCall").defaultValue = "23:30";
document.getElementById("timeOfResponse").defaultValue = "01:30";
</script>
</body>
</html>

Hello I have change your code slightly. The explanation is, let your start time is 10:00 and end time is 09:00. Now think with clock wise. the time had to go to 9:00 with 24 hours. So the calculation is difference between 24 and 10 hours and add the rest of the time.
D = E + (24 - S)
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
diff = eMin + (24 * 60 - sMin); /* You had to caculate with 24 hours */
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">

Here is another simpler way to look at the problem which satisfies all of your test cases, try your all test cases if any case fails then tell me i will fix it.
you just take the hours first and then check if is am or pm and then simply count the minutes.
function diffTime(start, end) {
var s = start.split(":");
var e = end.split(":");
var dHour;
var dMinute ;
var startHour = parseInt(s[0]);
var endHour = parseInt(e[0]);
var startMinute = parseInt(s[1]);
var endMinute = parseInt(e[1]);
// For counting difference of hours
if((startHour>12 && endHour>12) || (startHour<12 && endHour<12))
{
if(startHour<endHour)
{
dHour = endHour - startHour;
}
else if(startHour>endHour)
{
dHour = 24 - ( startHour - endHour);
}
else
{
dHour = 24;
}
}
else if(startHour>12 && endHour<=12)
{
dHour = (24 - startHour) + endHour;
}
else if(startHour<=12 && endHour > 12)
{
dHour = endHour - startHour;
}
else
{
dHour = 24
}
// For Counting Difference of Minute
if (startMinute>endMinute)
{
dMinute = 60 - (startMinute - endMinute);
dHour = dHour - 1;
}
else if(startMinute<endMinute)
{
dMinute = endMinute - startMinute;
}
else
{
dMinute = 0
}
return dHour + " Hours " + dMinute + " Minutes";
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="text" id="delay">

thank you friend i solve my problem, Miraz Chowdhury's code has done my job

function diff(t1, t2) {
const day = 86400000;
function pad(num) {
return ("0" + num).slice(-2);
}
let time1 = t1.split(":").map(el => parseInt(el));
let time2 = t2.split(":").map(el => parseInt(el));
let zero = (new Date(1990, 0, 1, 0, 0)).setMilliseconds(0)
let aaa = (new Date(1990, 0, 1, time1[0], time1[1])).setMilliseconds(0)
let bbb = (new Date(1990, 0, 1, time2[0], time2[1])).setMilliseconds(0)
let diff = day -Math.abs(aaa - bbb)<Math.abs(aaa - bbb)?day -Math.abs(aaa - bbb):Math.abs(aaa - bbb)
return `${pad(Math.round(diff/1000/60/60))}:${pad(Math.abs(Math.round(diff/1000/60%60)))}`;
}
console.log(diff("09:00", "08:00"));
console.log(diff("23:30", "01:30"));
console.log(diff("01:30", "23:30"));

Related

Subtract time and show difference in mins:secs format

I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss
methods: {
calcuateTimeDifference: function (startTime, endTime) {
let result = 0;
if (startTime && endTime) {
let start = startTime.split(":");
let end = endTime.split(':');
let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
result = endTimeInHrs - startTimeInHrs;
}
return result.toFixed(2);
},
Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.
split the strings on : to get the hours, minutes, and seconds
convert all to seconds and add them to get the total seconds from each time
subtract the two to get the difference in seconds
convert the difference seconds to hours, minutes and seconds using the modules operator(%)
format the result for appropriate display
let start = "16:03:01";
let end = "16:04:05";
let time = calcuateTimeDifference(start, end);
console.log(time);
function calcuateTimeDifference(startTime, endTime) {
let result = 0;
if (startTime && endTime) {
const start = startTime.split(':').map(Number);
const end = endTime.split(':').map(Number);
const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];
const diffSeconds = endSeconds - startSeconds;
seconds = parseInt((diffSeconds) % 60);
minutes = parseInt((diffSeconds/60) % 60);
hours = parseInt((diffSeconds/(60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
console.log("Invalid Input");
}
function calcuateTimeDifference(startTime, endTime) {
let toSeconds = (time) => {
let [h, m, s] = time.split(':');
return h * 360 + m * 60 + +s;
};
let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));
let mm = String(Math.floor(d / 60));
if (mm.length == 1) mm = '0' + mm;
let ss = String(d % 60);
if (ss.length == 1) ss = '0' + ss;
return `${mm}:${ss}`;
}

Javascript Countdown Timer with User input

I am trying to create a countdown timer where the user can input any combination of day, hour, minute, and seconds values and have it countdown to completion. I feel like I've got all the pieces but after a week of trying to solve this issue, I need help. I shuffle code around all with varying effects. Basically I feel like I'm missing a way to format the input data in a way I can use to subtract from the current date, but honestly I have no idea. Any input would be helpful.
Javascript:
function start() {
var countdownTimer = setInterval('timer()', 1000);
}
function timer() {
var d = parseInt(document.getElementById("days").value, 0);
var h = parseInt(document.getElementById("hours").value, 0);
var m = parseInt(document.getElementById("minutes").value, 0);
var s = parseInt(document.getElementById("seconds").value, 0);
var now = new Date();
var date = now.getTime();
addDay = now.setDate(now.getDate() + d);
addHour = now.setHours(now.getHours() + h);
addMinute = now.setMinutes(now.getMinutes() + m);
addSecond = now.setSeconds(now.getSeconds() + s);
var then = new Date(addHour + addMinute + addSecond);
if(d > 0 || h > 0 || m > 0 || s > 0){
var final = then - date;
var dd = Math.floor(final/ (1000 * 60 * 60 * 24));
var hh = Math.floor((final / (1000 * 60 * 60)) % 24);
var mm = Math.floor((final / 1000 / 60) % 60);
var ss = Math.floor((final / 1000) % 60);
document.getElementById("display").innerHTML = "Time Remaining: " + dd + "D " + hh + "H " + mm + "M " + ss + "S";
document.getElementById("message").innerHTML = then;
if (final < 0) {
clearInterval(countdownTimer);
document.getElementById("message").innerHTML = "Expired";
}
}else{
document.getElementById("display").innerHTML = " ";
document.getElementById("message").innerHTML = "Countdown Not Started";
}
}
HTML:
<div id="countdowntimer">
<button id="Start" onclick="start();">Start Timer</button>
D:<input type="text" id="days" value="0" />
H:<input type="text" id="hours" value="0" />
M:<input type="text" id="minutes" value="0" />
S:<input type="text" id="seconds" value="0" /><br>
<div id="display"></div>
<div id="message"></div>
</div>
If your timer is not based on date but on a given number of days, hours, minutes and seconds, why involve dates at all ? How about
function timer(){
var d = parseInt(document.getElementById("days").value, 0);
var h = parseInt(document.getElementById("hours").value, 0);
var m = parseInt(document.getElementById("minutes").value, 0);
var s = parseInt(document.getElementById("seconds").value, 0);
var current = ((d * 86400) + (h * 3600) + (m * 60) + s); //the current time left in seconds
if (current > 0) {
//take one second away, and rerender the seconds split into d, h, m, and s in the html, which you will reuse next time timer() runs
} else {
//expired
}
}

How to calculate the hours between two times with jquery?

I am trying to calculate the hours between two times.
Below is where I am currently but this code fails in two ways.
1). I need .Hours to output time in decimal.
(e.g one and half hours should output 1.5 and 15mins should be 0.25).
2). Calculation currently does not treat values for time as time.
(e.g 23:00 to 2:00 should equal 3 and NOT -21 as currently).
HTML
<input class="Time1" value="10:00" />
<input class="Time2" value="12:00" />
<input class="Hours" value="0" />
JQUERY
$(function () {
function calculate() {
var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
$(".Hours").val(hours);
}
$(".Time1,.Time2").change(calculate);
calculate();
});
http://jsfiddle.net/44NCk/
Easy way is if you get a negative value, add 24 hours to it and you should have your result.
var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
// if negative result, add 24 hours
if(hours < 0) hours = 24 + hours;
Demo: http://jsfiddle.net/44NCk/1/
Getting the minutes as a decimal involves a bit more as you can see in thsi fiddle: http://jsfiddle.net/44NCk/2/
function calculate() {
var time1 = $(".Time1").val().split(':'), time2 = $(".Time2").val().split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
var hours = hours2 - hours1, mins = 0;
// get hours
if(hours < 0) hours = 24 + hours;
// get minutes
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
// convert to fraction of 60
mins = mins / 60;
hours += mins;
hours = hours.toFixed(2);
$(".Hours").val(hours);
}
function timeobject(t){
a = t.replace('AM','').replace('PM','').split(':');
h = parseInt(a[0]);
m = parseInt(a[1]);
ampm = (t.indexOf('AM') !== -1 ) ? 'AM' : 'PM';
return {hour:h,minute:m,ampm:ampm};
}
function timediff(s,e){
s = timeobject(s);
e = timeobject(e);
e.hour = (e.ampm === 'PM' && s.ampm !== 'PM' && e.hour < 12) ? e.hour + 12 : e.hour;
hourDiff = Math.abs(e.hour-s.hour);
minuteDiff = e.minute - s.minute;
if(minuteDiff < 0){
minuteDiff = Math.abs(60 + minuteDiff);
hourDiff = hourDiff - 1;
}
return hourDiff+':'+ Math.abs(minuteDiff);
}
difference = timediff('09:10 AM','12:25 PM'); // output 3:15
difference = timediff('09:05AM','10:20PM'); // output 13:15
$(function () {
function calculate() {
var time1 = $(".Time1").val().split(':'), time2 = $(".Time2").val().split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10),
seconds1 = parseInt(time1[2], 10),
seconds2 = parseInt(time2[2], 10);
var hours = hours2 - hours1, mins = 0, seconds = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
if (seconds2 >= seconds1) {
seconds = seconds2 - seconds1;
}
else {
seconds = (seconds2 + 60) - seconds1;
mins--;
}
seconds = seconds/60;
mins += seconds;
mins = mins / 60; // take percentage in 60
hours += mins;
//hours = hours.toFixed(4);
$(".Hours").val(hours);
}
$(".Time1,.Time2").change(calculate);
calculate();
});
Here is an HTML Code
<input type="text" name="start_time" id="start_time" value="12:00">
<input type="text" name="end_time" id="end_time" value="10:00">
<input type="text" name="time_duration" id="time_duration">
Here is javascript code
function timeCalculating()
{
var time1 = $("#start_time").val();
var time2 = $("#end_time").val();
var time1 = time1.split(':');
var time2 = time2.split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
var hours = hours2 - hours1, mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
if(mins < 9)
{
mins = '0'+mins;
}
if(hours < 9)
{
hours = '0'+hours;
}
$("#time_duration").val(hours+':'+mins);
}

Calculate Time Difference with JavaScript

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * (1000 * 60 * 60);
var minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})

Time Duration problem for 12 hrs format

I am getting the time duration correctly for 24 hrs format but for 12 hrs format I am getting error if i give 11:00 am to 1:00 pm. If I give 10:00 am to 11:00 am it will correctl and if I give 6:00 pm to 7:00 pm it will give correctly only in am to pm i m facing problem.
function autoChangeDuration() {
var diff1 = "00:00";
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
if (start > end) {
document.getElementById("duration").value = diff1;
} else {
var space1 = start.split(' ');
var space2 = end.split(' ');
s = space1[0].split(':');
e = space2[0].split(':');
var diff;
min = e[1] - s[1];
hour_carry = 0;
if (min < 0) {
min += 60;
hour_carry += 1;
}
hour = e[0] - s[0] - hour_carry;
diff = hour + ":" + min;
document.getElementById("duration").value = diff;
}
function toDate(s) {
// the date doesn't matter, as long as they're the same, since we'll
// just use them to compare. passing "10:20 pm" will yield 22:20.
return new Date("2010/01/01 " + s);
}
function toTimeString(diffInMs) {
// Math.max makes sure that you'll get '00:00' if start > end.
var diffInMinutes = Math.max(0, Math.floor(diffInMs / 1000 / 60));
var diffInHours = Math.max(0, Math.floor(diffInMinutes / 60));
diffInMinutes = diffInMinutes % 60;
return [
('0'+diffInHours).slice(-2),
('0'+diffInMinutes).slice(-2)
].join(':');
}
function autoChangeDuration()
{
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
start = toDate(start);
end = toDate(end);
var diff = (end - start);
document.getElementById("duration").value = toTimeString(diff);
}
Why don't you just use javascript's Date class?
http://www.w3schools.com/jsref/jsref_obj_date.asp

Categories

Resources