I have 2 dates in ISO format like so:
startDate: "2018-09-14T00:20:12.200Z"
endDate: "2018-09-16T00:18:00.000Z"
What I'm trying to do is calculate the difference between those 2 days. So with the given dates it would be 1 Day, 21 Hours, 47 Minutes and 40 Seconds (pardon me if the subtraction is not correct).
Tried to do using the following:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return Math.abs(end - start).toString();
However this doesn't seem to work.
Any clues?
The following works. Things to note:
getTime() is not needed as the new Date() constructor returns the time in milliseconds.
The date should always be in RFC2822 or ISO formats, else it becomes useless across various browsers, even while using moment.js.
If you can use moment.js, Get time difference using moment.
Refer this to know why only the standardized formats need to be used.
var unitmapping = {"days":24*60*60*1000,
"hours":60*60*1000,
"minutes":60*1000,
"seconds":1000};
function floor(value)
{
return Math.floor(value)
}
function getHumanizedDiff(diff)
{
return floor(diff/unitmapping.days)+" days "+
floor((diff%unitmapping.days)/unitmapping.hours)+" hours "+
floor((diff%unitmapping.hours)/unitmapping.minutes)+" minutes "+
floor((diff%unitmapping.minutes)/unitmapping.seconds)+" seconds "+
floor((diff%unitmapping.seconds))+" milliseconds";
}
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-14T00:20:12.200Z")));
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-04T00:20:02.630Z")));
console.log(getHumanizedDiff(new Date("2018-09-17T00:16:04.000Z") - new Date("2018-09-14T00:20:12.240Z")));
var startDate = "2018-09-14T00:20:12.200Z"
var endDate = "2018-09-16T00:18:00.000Z"
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const milliseconds = Math.abs(end - start).toString()
const seconds = parseInt(milliseconds / 1000);
const minutes = parseInt(seconds / 60);
const hours = parseInt(minutes / 60);
const days = parseInt(hours / 24);
const time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60;
console.log(time)
yBrodsky's suggestion to use moment.js is probably the best idea, but if you're curious how to do the math here, it would go something like this:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
let seconds = Math.round(Math.abs(end - start) / 1000); // We'll round away millisecond differences.
const days = Math.floor(seconds / 86400);
seconds -= days * 86400;
const hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
This leaves you with hours, minutes, and seconds as numbers that you can format into a string result however you like.
Related
I have two sample unix timestamps that I'm trying to find the difference for in hours/minutes/seconds. One is a current time from TypeScript and one is an expiration time within 24 hours after. I just want to print out the time left until expiration.How do I go about this in TypeScript and Node?
current_time = 1633115367891
exp_time = 01633201203
You can convert unix timestamp to milliseconds timestamp and take their delta. Then convert the delta to hh:mm:ss format.
const current_time = 1633115367891,
exp_time = 1633201203,
diff = (exp_time * 1000) - current_time,
formatTime = (ms) => {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600) % 24);
return [hours, minutes, seconds].map(v => String(v).padStart(2,0)).join(':');
}
console.log(formatTime(diff));
What is the best way to get time for recent notifications (relative to current time) in an application, which are 5 sec ago, 10 sec ago or 7 hr 32 min ago?
In other words, I have a Date Object (in format 2019-03-12T10:05:32.257) which is for example 3 hr 6 min 9 sec ago from current time, I am wondering if there is a clean way to achieve the magic numbers 3, 6, 9 and display in html.
More cleaner way and generic implementation that I see to approach this problem could be.
Get the difference of date object in seconds converted as a first step
Then check for whether it could be fit into
years(divide by 31536000)
months(divide by 2592000)
days(divide by 86400)
hours(divide by 3600)
minutes(divide by 60)
function timesAgo(date) {
var seconds = Math.floor((new Date() - date) / 1000); // get the diffrence of date object sent with current date time of the system time
var interval = Math.floor(seconds / 31536000); // divide seconds by seconds in avg for a year to get years
//conditioning based on years derived above
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000); // months check similar to years
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400); // days check similar to above
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600); // hours check
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60); // minutes check
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds"; // seconds check at the end
}
var withYears = new Date('August 19, 1999 23:15:30');
var withMonths = new Date('March 19, 2019 23:15:30');
var withDays = new Date('May 1, 2019 23:15:30');
var withPreviousDay = new Date('May 5, 2019 23:15:30');
var withHours = new Date('May 6, 2019 10:15:30');
console.log(timesAgo(withYears));
console.log(timesAgo(withMonths));
console.log(timesAgo(withDays));
console.log(timesAgo(withPreviousDay));
console.log(timesAgo(withHours));
Easier way If your using Angular and Moment is to use fromNow() function - Link
console.log(moment([2007, 0, 29]).fromNow(true)); // 12 years
console.log(moment([2007, 0, 29]).fromNow()); // 12 years ago
<script data-require="moment.js#*" data-semver="2.18.0" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
If you need an Angular Pipe check this times-ago-pipe
I guess you are trying to find the difference between two Date objects.
First, you can convert them to Date objects, followed by using getTime() to get it in milliseconds. After which, you subtract both date objects to get the time difference, and then divide it by 1000 to get the results in seconds.
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
From there, you can convert it to your required format (hours, minutes, and seconds).
And in order to convert them into hours, minutes and seconds,
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
This is how the end result will be like:
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
const result = `${hours} hr ${minutes} min ${seconds} sec`
console.log(result);
I have a silly issue with time difference in moments.js.
Code to get time difference
var to = '2019-02-03 01:55:00'; //When counter ends
var start = moment(); //Current time, for this example assume is '2019-02-03 01:53:00'
var end = moment(to);
var seconds = end.diff(start, 'seconds', true); //get difference in seconds, the third params is to get not rounded, but since in toMMSS function I do parseInt is useless
var formatted = toMMSS(seconds);
function to format seconds:
var toMMSS = function (seconds) {
var sec_num = parseInt(seconds, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return minutes+':'+seconds;
};
Now the expected output is 02:00, but some people get 02:05 or 02:07 or 02:03 but the output for '2019-02-03 01:55:00' - '2019-02-03 01:53:00' should be (logically) 02:00
P.S. moment.js defaults:
moment.tz.setDefault('Europe/Moscow');
moment.defaultFormat = "YYYY-MM-DD HH:mm:ss";
var end is also in that timezone.
I tried others ways of calculating the difference, but get the same result, it can be that on some PCs/Browser this is not accurate, if yes maybe there is a workaround to not rely on user PC time?
Any help appreciated.
I need to get time difference in this format: "HH:MM:SS" using a Javascript.
I have tried this:
var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
and this:
var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
These are the values of time2 and time1:
time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"
And result I am getting in both cases is:
total_time= 0.5250819444444444:31.504916666666666:1890.295
Which you can see is not correct
I think you are getting wrong diff value because of the millisecond part in the date delimited by .. Its not being accepted correctly by the data parser.
Try using the date and time part excluding the milliseconds as below:
var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);
Also while you are getting wrong difference diff, your time computation is also wrong.
It should be:
var second = Math.floor(diff /1000);
//convert the seconds into minutes and remainder is updated seconds value
var minute = Math.floor(second /60);
second = second % 60;
//convert the minutes into hours and remainder is updated minutes value
var hour = Math.floor(minute/60);
minute = minute %60;
var total_time= hour+":" minute+":"+second;
You forgot to remove the number of milliseconds you already calculated from diff. Here is a very verbose example on how you do it in a propper way.
var time1 = "2012-11-07 15:20:32.161",
time2 = "2012-11-07 17:55:41.451",
SECOND = 1000,
MINUTE = SECOND* 60,
HOUR = MINUTE* 60;
var diff = new Date(time2) - new Date(time1);
var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;
var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;
DEMO
lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).