This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 3 years ago.
I need a timer for my program so my idea was to use the Date() and a future date to make the difference between them a timer,but i have been having problems with Date() functions,where the future returns null
var date = new Date();
var future = date.setMinutes(date.getMinutes + 3);
console.log(future); //prints NAN
var distance = future - date;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
use getMinutes as a method call and add 3 to that.
let future = new Date((date = new Date()).setMinutes(date.getMinutes() + 3));
let future = new Date((date = new Date()).setMinutes(date.getMinutes() + 3));
console.log(future.toLocaleString());
use getMinutes as a method call, not a property, and add 3 to that.
let future = new Date((date = new Date()).setMinutes(date.getMinutes() + 3));
let future = new Date((date = new Date()).setMinutes(date.getMinutes() + 3));
console.log(future);
Related
This question already has answers here:
JavaScript - Get minutes between two dates
(12 answers)
Difference between dates, rounded result to nearest minute
(3 answers)
Closed 2 years ago.
I have the following date string: 2020-04-21T15:28:26.000Z
I would like to convert it into the amount of hours and minutes that have passed since that.
For example: 5:10
function getPassedTime(dateStr){
const date = new Date(dateStr);
const now = new Date();
var diff = now.getTime() - date.getTime();
var diffInMinutes = Math.round(diff / 60000);
var hours = (diffInMinutes / 60);
var passeHours = Math.floor(hours);
var minutes = (hours - passeHours) * 60;
var passedMinutes = Math.round(minutes);
return passeHours+":"+passedMinutes;
}
console.log(getPassedTime('2020-04-21T15:28:26.000Z'))
function getDiffTime(time) {
const old = new Date(time)
const now = new Date();
const diff = now - old;
const msInHrs = 1000 * 60 * 60;
const msInMn = 1000 * 60;
const hrs = Math.floor(diff / msInHrs);
const mn = Math.floor((diff % (hrs * msInHrs)) / msInMn);
return `${hrs}:${mn}`;
}
console.log(getDiffTime('2020-04-21T15:28:26.000Z'));
This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
Closed 3 years ago.
I want to get the number of years and months using Javascript, but I am not able to get to get them:
var date=new Date("2018-09-02")
document.body.innerHTML=calculateAge(date) //should print 1.1 year(s)
function calculateAge(date) {
var ageDifMs = Date.now() - date;
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
View JSFiddle
I have researched a lot, but I wasn't able to find the right approach to print the difference in yy.mm format which is indicating year and months.
You should check the conversions first before asking... Here
function toYear(dateOne, dateTwo){
var milToYear = 1000 * 60 * 60 * 24 * 365 // 1000 to 1 sec * 60 for 60 sec * 60 for min * 24 for hours 365
var difDate = dateOne.getTime() - dateTwo.getTime();
var result = difDate / milToYear;
console.log(result);
return result;
}
var date = new Date();
var date2 = new Date('2018-09-02');
toYear(date, date2);
var date = new Date("2018-09-02");
var age = calculateAge(date);
document.body.innerHTML = age;
function calculateAge(date) {
var dateNow = Date.now();
// To calculate the time difference of two dates
var Difference_In_Time = dateNow - date.getTime();
console.log("Difference_In_Time : " + Difference_In_Time);
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
console.log("Difference_In_Days: " + Difference_In_Days);
// To calculate difference in Years
var Difference_In_Years = Difference_In_Days / 365
console.log("Difference_In_Years: " + Difference_In_Years);
return Difference_In_Years;
}
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);
So I have an array of dates and want to get the current date and put it into a countdown clock
I have this code atm:
<script>
var dates = [
'24/5/2017',
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
];
function sortDates(dates) {
return dates.map(function(date) {
return new Date(date).getTime();
}).sort(function(a, b) {
return a - b;
});
}
var orderedDates = sortDates(dates);
document.getElementById("demoo").innerHTML = orderedDates
var nextDate = orderedDates.filter(function(date) {
return (var now = new Date().getTime(); - date) > 0;
})[0];
document.getElementById("demo").innerHTML = nextDate
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = nextDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
<center><h2>Core Maths 2</h2><center>
This doesn't seem to do anything, so I don't really know what to do. at the moment it just comes up with NAN for the countdown
One problem is, that, for instance, new Date('24/5/2017') yields Invalid Date. I don't think this is a valid Date format recognized by new Date().
If you really need the format like this, you can do something like:
var dates = [
'24/5/2017', // past Date for testing
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
].map(function (d) {
var parts = d.split('/');
return new Date(parts[2], parts[1] - 1 /* january = 0 */, parts[0]);
});
so you end up having actual Date objects instead of strings by passing the parameters in a order to the Date constructor which it understands.
Another point: Since you can interpret a Date object as a Number (which yields the same as new Date().getTime(), namely the milliseconds since January 1, 1970), you can simply get the minimum using: Math.min.apply(Math, dates). So, your "next Date" (smallest timestamp which is not in the past) can simply been retrieved by var nextDate = new Date(Math.min.apply(Math, dates.filter(x => +x > Date.now())));
Below is a working snipppet which should do what you wanted.
var dates = [
'20/4/2017',
'24/5/2017',
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
].map(function (d) {
var parts = d.split('/');
return new Date(parts[2], parts[1] - 1 /* january = 0 */, parts[0]);
});
var nextDate = new Date(Math.min.apply(Math, dates.filter(x => +x > Date.now())));
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = nextDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<center><h2>Core Maths 2</h2><center>
<div id="demo"></div>
So I did your dirty work for you, all you needed to do is some debugging, putting some console logs here and there to find out what was going wrong, which was a couple of things.
1. Your date formats are messed up (at least for me).
Instead of typing '24/5/2017', type '5/24/2017' if you want it to go right when you pass it into a Date() constructor. You can validate this by doing this: console.log(new Date('24/5/2017'));
2. Your filter function was bad
You want the next date, though you check for now - date > 0 which means that only dates that were in past will work. Either use date - now > 0 or now - date < 0.
3. You made a typo
document.getElementById("demoo").innerHTML = orderedDates
Notice the extra 'o' in 'demoo'.
4. You used invalid syntax
var nextDate = orderedDates.filter(function(date) {
return (var now = new Date().getTime(); - date) > 0;
})[0];
This doesn't work because you cannot declare now like this. Extract the declaration of now to a line above the return statement as follows:
var nextDate = orderedDates.filter(function(date) {
var now = new Date().getTime();
return (now - date) < 0;
})[0];
If you apply all these corrections your countdown should work.
I am building an Instagram feed with JQuery into my site and want to show how long has passed since the post was submitted in a short form like: 23H or 2D or 3M or 1Y depending on how long its been. I've got my two date objects but I can't figure our how to calculate the difference and display it how i want.
I am fairly new to JS/Jquery and as far as i could get was:
var pd = new Date(postDate);
var nd = new Date();
var nd = nd.getTime();
var difference = nd-pd;
How do I calculate the difference between two dates in hours, days, months and years?
Thanks.
Doing anything with dates is generally painful.
If you aren't committed to using that exact format, you can use a library for this instead.
moment.js has a .fromnow() function.
or timeago.js can be used to update the element on the page periodically, so if the user leaves the page open for a few minutes, the time stamps will count up.
You can do this to get the time elapsed since posted
var timeDiff = Math.abs(nd.getTime() - pd.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
you can try like this.
var pd = new Date(postDate);
var nd = new Date();
var Hours = nd.getHours() - pd.getHours();
var Days = nd.getDay() - pd.getDay();
var Months = nd.getMonth() - pd.getMonth();
var Years = nd.getYear() - pd.getYear();
or get millisecods diference
var miliseconds = (nd - pd).getTime(); //gets time in miliseconds since 1/1/1970
then use your logic to calculate hours, days, months and years
you can have a look at this Work with a time span in Javascript
moments
ar date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
My solution is dirty but direct: calculate them by myself.
Record start time:
var BEGIN_TIME=new Date();
var HOUR=BEGIN_TIME.getHours();
var MINUTE=BEGIN_TIME.getMinutes();
var SECOND=BEGIN_TIME.getSeconds();
Then do so some math
var today=new Date();
h=today.getHours();
m=today.getMinutes();
s=today.getSeconds();
s = s - SECOND;
if (s<0) { s=s+60; m=m-1; }
m = m - MINUTE;
if (m<0) { m=m+60; h=h-1; }
h = h - HOUR;