This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 7 years ago.
I'm trying to subtract two times from each other and for the most part works but in some scenarios it's giving the wrong output.
Here's my code so far:
//postDateTime looks like 2015-04-23T22:23:32.902Z
//Split the date and time
var postDateTime2 = postDateTime.split("T");
//remove the Z from the post time stamp
postDateTime2[1] = postDateTime2[1].replace('Z','');
//split the post date/time into sperate variables
var postDate = postDateTime2[0]; // date
var postTime = postDateTime2[1]; // time
//split up the post time into hours, minutes, seconds
var postTimeSplit = postTime.split(":");
var postTimeHour = postTimeSplit[0];
var postTimeMinutes = postTimeSplit[1];
var postTimeSeconds = postTimeSplit[2];
//split the date to have year, month, date separate
var postDateSplit = postDate.split("-");
//split the post date to year, month, date
var postYear = postDateSplit[0]; //year
var postMonth = postDateSplit[1]; //month
var postDate2 = postDateSplit[2]; //date
//get the current hour, minutes, seconds in UTC time.
var hours = now.getUTCHours();
var minutes2 = now.getUTCMinutes();
var seconds2 = now.getUTCSeconds();
//get the difference in years between post time and response time
var responseYear = Math.abs(now.getUTCFullYear() - postYear);
//get the difference in months between post time and response time
var responseMonth = Math.abs(mm - postMonth);
//get the difference in days between post time and response time
var responseDate = Math.abs(now.getUTCDate() - postDate2);
//get the difference in hours between post time and response time
var responseHour = Math.abs(now.getUTCHours() - postTimeHour);
//get the difference in minutes between post time and response time
var responseMinutes = Math.abs(now.getUTCMinutes() - postTimeMinutes);
//get the difference in seconds between post time and response time
var responseSeconds = Math.abs(now.getUTCSeconds() - postTimeSeconds);
Math.round(responseSeconds); // round the seconds to up to 2 decimal (doesn't work as expected)
So like I said, it works but if the time difference is more than one hour, it's starts giving weird outputs. For example if the real time difference has been only 38 minutes and the current time is an hour ahead, it will count it as 1 hours and 22 minutes.
Any suggestions how I can do this better?
So after some more research and thanks to Jasen, it was easier to convert my current time to a RFC 3339 time stamp and then find the difference that way in milliseconds and convert it back to a date. I also did some additional formatting for readability. Here's my final code:
//current time in RFC 3339 timestamp
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
var currentTime = ISODateString(d);
//assign vars for current hour, minutes, seconds in UTC time.
var hours = d.getUTCHours();
var minutes = d.getUTCMinutes();
var seconds = d.getUTCSeconds();
//parse both time stamps into dates
var finalCurrentTime = Date.parse(currentTime);
var finalPostDateTime = Date.parse(postDateTime);
//find the difference between the original post date/time and the current date/time (in milliseconds)
var responseTimeFinal = Math.abs(finalCurrentTime - finalPostDateTime);
function dhm(ms){
var days2 = Math.floor(ms / (24*60*60*1000));
var daysms=ms % (24*60*60*1000);
var hours2 = Math.floor((daysms)/(60*60*1000));
var hoursms=ms % (60*60*1000);
var minutes2 = Math.floor((hoursms)/(60*1000));
var minutesms=ms % (60*1000);
var sec = Math.floor((minutesms)/(1000));
days2 = (days2 < 10) ? "0" + days2 : days2;
hours2 = (hours2 < 10) ? "0" + hours2 : hours2;
minutes2 = (minutes2 < 10) ? "0" + minutes2 : minutes2;
sec = (sec < 10) ? "0" + sec : sec;
//format day
if (days2 === "00"){
days2 = "";
} else if (days2 === "01"){
days2 = days2 + " day, ";
}
else if (days2 > "01"){
days2 = days2 + " days, ";
}
//format hours
if (hours2 === "00"){
hours2 = "";
}
else if (hours2 === "01"){
hours2 = hours2 + " hour, ";
}
else if (hours2 > "01"){
hours2 = hours2 + " hours, ";
}
//format minutes
if (minutes2 === "01"){
minutes2 = minutes2 + " minute, ";
}
else if (minutes2 > "01"){
minutes2 = minutes2 + " minutes, ";
}
//format seconds
if (sec === "01"){
sec = sec + " second";
}
else if (sec > "01"){
sec = sec + " seconds";
}
return days2+""+hours2+""+minutes2+""+sec;
}
//pass the milliseconds from responseTimeFinal into the dhm function to convert it back to a date
var timeDifference = dhm(responseTimeFinal);
console.log(timeDifference); // our final result that works!
Related
I've been trying to implement the function that sums two values as hours.
"Example: 01:30 + 00:30 = 02:00"
So I have this function below that works only if the sum of the two values is equal to a round number such as the example above. But the problem is when the values are say 01:45 + 00:20 it gives me 33:05 instead of 02:05.
I've tried several combinations but nothing has worked so far.
function sumOFHoursWorked(){
var time1 = "00:45";
var time2 = "01:20";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2]);
minute = minute + second/60;
second = second%60;
var REalhourstime = ('0' + hour).slice(-2)+':'+('0' + minute).slice(-2);
alert(REalhourstime);
document.getElementById('realhorasTB').innerHTML = REalhourstime;
}
It actually depends on how your time will be, i mean it will be in mm:ss formet or hh:mm:ss or maybe hh:mm:ss:msms but for just simple second and minutes you can do something like this
function sumOFHoursWorked(){
var time1 = "00:45".split(':');
var time2 = "01:20".split(':');
let secondSum = Number(time1[1]) + Number(time2[1]);
let minSum = Number(time1[0]) + Number(time2[0]);
if(secondSum > 59){
secondSum = Math.abs(60 - secondSum);
minSum += 1;
}
if(secondSum < 10){
secondSum = `0${secondSum}`;
}
if(minSum < 10){
minSum = `0${minSum}`;
}
return `${minSum}:${secondSum}`;
}
console.log(sumOFHoursWorked());
I would convert it to minutes and subtract and then calculate hours and minutes.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("00:45", "01:20"))
It will fail for times that go over midnight, a simple less than check can fix that.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
if (mins2 < mins1) {
mins2 += 1440
}
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("23:45", "00:45"))
First of all, the time1 and time2 strings are missing the seconds at the end. For example, var time1 = "00:45:00". Otherwise, your calculation will have some NaN values.
The main issue is that hour is a floating point number (~ 2.083333333333333), so ('0' + hour) is '02.083333333333333'.
You could use something like this instead: ('0' + Math.floor(hour)).
I need to calculate time difference in hrs in between current date time and user input date time using JavaScript. Here is my code:
var user_date = '31-03-2019';
var dep_time='12:30PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = '0' + todayDay;
}
if (todayMonth < 10) {
todayMonth = '0' + todayMonth;
}
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(mydate);
var todayToDate = Date.parse(todayDateText);
//console.log(inputToDate, todayToDate);
//console.log(user_date, todayDateText);
if (inputToDate > todayToDate) {
var date=new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var timeStart = new Date(todayToDate + strTime);
var timeEnd = new Date(mydate + dep_time);
console.log(timeStart);
console.log(timeEnd);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
alert(hours);
} else {
}
Here I getting the output NAN . I have both user input and current date time and I need the time difference in HRS.
1) The Date.parse method turns a date into milliseconds since January 1st, 1970. See https://www.w3schools.com/Jsref/jsref_parse.asp, therefore turning your user input date into milliseconds since January 1st, 1970.
2) In Javascript, the getTime() method on the new Date() object gets the number of milliseconds that have passed since January 1, 1970 until the current time.
3) Therefore, finding the difference of these milliseconds gives you the difference in milliseconds.
4) Since 1 hour = 3600000 ms, to find the difference in hours, divide your answer by 3600000, and get the difference in hours.
You also seem to forget to include the dep_time in parsing your date.
And the solution is below:
<script>
"use strict";
var user_date = '31-03-2019 12:30 PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayToDate = todayDate.getTime();
// In JavaScript, getTime() gets the number of milliseconds that have passed since January 1, 1970.
var inputToDate = Date.parse(mydate);
if (inputToDate > todayToDate) {
var diff = (inputToDate - todayToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
} else {
var diff = (todayToDate - inputToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
}
</script>
I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()
Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>
I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));