Jquery - Get the time in HH:MM format between two dates - javascript

I am getting the values from two text fields as date
var start_actual_time = $("#startPoint_complete_date").val();
var end_actual_time = $("#endPoint_complete_date").val();
which gives value
start_actual_time = 01/17/2012 11:20
end_actual_time = 01/18/2012 12:20
now i want to find out the duration in HH:MM format between these two dates (which is 25:00 in this case)
how can i do it...

var start_actual_time = "01/17/2012 11:20";
var end_actual_time = "01/18/2012 12:25";
start_actual_time = new Date(start_actual_time);
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time - start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
alert(formatted);
See demo : http://jsfiddle.net/diode/nuv7t/5/ ( change mootools in jsfiddle
or open http://jsfiddle.net/nuv7t/564/ )

Working example:
gives alert message as 6:30
$(function(){
var startdate=new Date("01/17/2012 11:20");
var enddate=new Date("01/18/2012 12:20");
var diff = new Date(enddate - startdate);
alert(diff.getHours()+":"+diff.getMinutes());
});

First, I recommend this: http://www.mattkruse.com/javascript/date/ to convert the string to a date object, but you can convert it any way you want. Once converted, you can do this:
var difference_datetime = end_datetime.getTime() - start_datetime.getTime()
The getTime() function gets the number of milliseconds since 1970/01/01. Now you have the number of milliseconds of difference, and you can do whatever you want to convert to higher numbers (eg. divide by 1000 for seconds, divide that by 60 for minutes, divide that by 60 for hours, etc.)

I did something simular on a blog to see how long im together with my gf :P
http://daystogether.blogspot.com/ and this is how I did it:
// *****Set the unit values in milliseconds.*****
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// *****Setting dates*****
var today = new Date();
var startDate = new Date('10/27/2011 11:00:00');
// *****Calculate time elapsed, in MS*****
var interval = today.getTime() - startDate.getTime();
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
var weeks = 0;
while(days >= 7)
{
days = days - 7;
weeks = weeks + 1;
}
var months = 0;
while(weeks >= 4)
{
weeks = weeks - 4;
months = months + 1;
}
// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds = Math.floor(interval / 1000 );
BTW this is just javascript, no jquery ;)

here you go:
function get_time_difference(start,end)
{
start = new Date(start);
end = new Date(end);
var diff = end.getTime() - start.getTime();
var time_difference = new Object();
time_difference.hours = Math.floor(diff/1000/60/60);
diff -= time_difference.hours*1000*60*60;
if(time_difference.hours < 10) time_difference.hours = "0" + time_difference.hours;
time_difference.minutes = Math.floor(diff/1000/60);
diff -= time_difference.minutes*1000*60;
if(time_difference.minutes < 10) time_difference.minutes = "0" + time_difference.minutes;
return time_difference;
}
var time_difference = get_time_difference("01/17/2012 11:20", "01/18/2012 12:20");
alert(time_difference.hours + ":" + time_difference.minutes);

start_date.setTime(Date.parse(start_actual_time));
end_date.setTime(Date.parse(end_actual_time));
//for check
start_date.toUTCString()
end_date.toUTCString()
/**
* Different in seconds
* #var diff int
*/
var diff = (end_date.getTime()-start_date.getTime())/1000;

Related

How can I calculate the difference between two times that are in 24 hour format which are in different dates?

In JavaScript, how can I calculate the difference between two times that are in 24 hour format which are having different dates?
Example:
Date1 is 2019/12/31 11:00:06 AM
Date2 is 2020/01/01 01:10:07 PM.
Time difference should be 02:10:13 in hh:MM:ss format
..how can get like this when date changes in appscript
Just use the Date
const dateDiffMs = (date1,date2 ) => {
const d1 = new Date(date1);
const d2 = new Date(date2);
return d1.getTime() - d2.getTime()
}
const ms2hms = (ms) => {
const sec = Math.floor(ms / 1000)
const min = Math.floor(sec / 60)
const h = Math.floor(min / 60)
return [
h,
min % 60,
sec % 60,
];
};
const format = (n) => n < 10 ? '0' + n : n;
const hms2str = ([h, min, sec]) => {
return `${h}:${format(min)}:${format(sec)}`
}
alert(hms2str(ms2hms(dateDiffMs('2020/01/01 01:10:07 PM', '2019/12/31 11:00:06 AM')))); // 26:10:01
This code works correctly if both date1 and date2 are in the same timezone. But i would recommend you to use moment.js or some other library
I would do this by gathering the date in second since whenever computers decided to keep track of time for us sometime in the 70's (epoch). Then pass it the second value and subtract, leaving the difference.
You would then need to convert it back to a date format I presume:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8);
console.log(timeDifferenceInDate);
}, 3000);
})();
NOTE: I have used a timeout function - you will already have two dates that do not match to pop in.
EDIT: having been notified the days will not be calculated, you could maybe use date to calculate your time in seconds then use Math to create your display:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
/* var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); */
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
timeDifferenceInDate = d + ':' + h + ':' + m + ':' + s;
console.log(timeDifferenceInDate);
}, 3000);
})();

how to know the result of substraction of date

I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.
I can't find correct search key for googling what I need.
Anyone know what should I search on google ? or someone knows some function about that?
PS. Mysql or Javascript
Try with date object in javascript
Like this
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:49")
var diff = Math.abs(d1-d2); // difference in milliseconds
Then convert the milliseconds to hours
var hours = parseInt((diff/(1000*60*60))%24);
You can go through it
Get the time difference between two datetimes
But the query is not clear do you want only the hour difference or you want the difference converted to hour format
Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?
here a code example of how to do it
var date1 = new Date("2017-07-25 09:30:49");
var date2 = new Date("2017-07-25 10:30:00");
var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();
console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateArray2= reggie.exec(dateString2);
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1); // difference in milliseconds
var hours = parseInt((diff/(1000*60*60))%24);
Try with the below dateFormatter function :
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:00")
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);
function dateFormatter(t){
var cd = 24 * 60 * 60 * 1000;
var ch = 60 * 60 * 1000;
var cm = 60*1000;
var d = Math.floor(t / cd);
var h = '0' + Math.floor( (t - d * cd) / ch);
var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}

JavaScript date difference correction

I have a function that will calculate time between two date / time but I am having a small issue with the return.
Here is the way I collect the information.
Start Date
Start Time
Ending Date
Ending Time
Hours
And here is the function that calculates the dates and times:
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)) {
alert("Input data is incorrect!");
return;
}
if (sec < 0) {
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000,
minute = 60 * second,
hour = 60 * minute,
day = 24 * hour;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
var min = Math.floor((minutes * 100) / 60);
document.getElementById("result").value = hours + '.' + min;
}
If I put in todays date for both date fields and then 14:30 in the first time field and 15:35 in the second time field the result is shown as 1.8 and it should be 1.08
I didn't write this function but I am wondering if someone could tell me how to make that change?
Thank you.
If I understand correctly, the only issue you are having is that the minutes are not padded by zeroes. If this is the case, you can pad the value of min with zeroes using this little trick:
("00" + min).slice(-2)
I can't see why 15:35 - 14:30 = 1.08 is useful?
Try this instead:
function timediff( date1, date2 ) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms/1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var hours = Math.floor(difference_ms % 24);
var days = Math.floor(difference_ms/24);
return [days,hours,minutes,seconds];
}
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var diff = timediff(date1, date2);
document.getElementById("result").value = diff[1] + ':' + diff[2];
}
Verify if number of minutes is less than 10 and if it is then append an additional zero in front. Follow similar approach for seconds.

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{
}
})

solve negative values in a javascript based countdown

I am creating a countdown to count the time between a match of the euro2012 that I intend to watch.
I've come with a working version of it but I don't understand why it gives me sometimes negative values.
I think it has to do with the way I wrote it, using the getTime() method.
Here is my code, could you guys help me find out to solve those negative values?
Thank you very much in advance.
<body onload="timeto2012()">
<script type="text/javascript">
function timeto2012() {
var euro2012 = new Date(2012, 5, 10, 20, 45);
var euro2012ms = euro2012.getTime();
var now = new Date();
var nowms = now.getTime();
var diff = euro2012ms - nowms;
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = diff/days;
var dhours = (ddays - Math.round(ddays,1))*24;
var dminutes = (dhours - Math.round(dhours))*60;
var dseconds = (dminutes - Math.round(dminutes))*60;
document.getElementById("time").innerHTML='' + Math.round(ddays,1) +' days '+ Math.round(dhours,1) +' hours '+ Math.round(dminutes,1) +' minutes '+ Math.round(dseconds,1) + ' seconds remaining';
}
t=setInterval(timeto2012,500);
</script>
<div id="time"></div>
</body>
KOGI has the answer to your problem: You should use Math.floor instead of Math.round:
When there's x minutes and 30 - 59 seconds left, the (x - Math.round(x)) would be equivalent to (x - (x + 1)) after the rounding was done.
var ddays = diff/days;
var dhours = (ddays - Math.floor(ddays))*24;
var dminutes = (dhours - Math.floor(dhours))*60;
var dseconds = (dminutes - Math.floor(dminutes))*60;
Fiddle: http://jsfiddle.net/YHktx/3/
Here are some better calculations for you (derived from Aleksi Yrttiaho's jsFiddle)
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = Math.floor( diff/days );
var dhours = Math.floor((diff % days) / hours );
var dminutes = Math.floor(((diff % days) % hours) / minutes );
var dseconds = Math.floor((((diff % days) % hours) % minutes) / seconds );

Categories

Resources