I am trying to get the amount of days relative to the current time, returning only days as units. So if something happened a week ago, it would say 7 days. If it happened 2 months ago, it would return that time in days as well.
I am aware of how to get there but I am having trouble putting the pieces together.
I have my days as a data attribute "data-order" so data-order="2019-4-2 00:00" or "2019-4-2" if it makes calculations easier.
$(".pop-cal").each(function (i, obj) {
moment.relativeTimeThreshold("m", 1);
moment.relativeTimeThreshold("d", 25 * 100);
var date = $(this).attr("data-order");
var momentDate = moment(date).fromNow();
$(this).attr("data-content", momentDate);
});
This is getting me dates, but they are always off.
My expected results would be similar confirmation to using google search and saying "58 days ago" and getting Tuesday February 12th 2019.
What I am currently getting as result are "59 days ago" on a moment time created on "2019-2-12.
The fromNow method isn't suitable if you need the exact number of days, because it works by converting the time to a Duration (measured in months and milliseconds), and then converting the Duration to a human readable form (humanize method).
As the Duration docs state:
It is much better to use moment#diff for calculating days or years
between two moments than to use Durations.
You can see the problem if you perform fromNow on February 28th and March 1st, 1 day apart but giving a fromNow of 4 days apart (due to 28 days in February instead of 31 days).
moment("2019-03-01").fromNow() // "45 days ago"
moment("2019-02-28").fromNow() // "49 days ago"
The moment#diff method can give you the exact difference between two moments in days, e.g. between moments a and b:
a.diff(b, 'days')
Related
I'm trying to get the difference between current local time and December 1, 2021 at 4 pm. There is a difference of 6 months and 2 hours. In this case I expect the answer to be something similar to 6.02. But 5.98 is coming. How can I get the answer I want?
enter image description here
According to the moment.js docs, the standard way to get the difference between two dates in your example would be now.diff(date, 'months', true), which should return a floating point number greater than 6.
now.diff(date) returns the millisecond difference between those two points in time. Calling moment.duration({milliseconds}).asMonths() is not ideal because some months may be 30 days long and others may be 31 days long. It appears that moment.js uses somewhere in between 30 and 31 days as the duration of one month. To address this issue, moment.js have discussed calendar diffs in the docs:
moment#diff has some special handling for month and year diffs. It is optimized to ensure that two months with the same date are always a whole number apart.
So Jan 15 to Feb 15 should be exactly 1 month.
Feb 28 to Mar 28 should be exactly 1 month.
Feb 28 2011 to Feb 28 2012 should be exactly 1 year.
The definition of "a month" can only be a "fuzzy" one, as the months of the calendar are of different lengths. One way of defining it would be to divide the year into 12 equal parts and use that as a "month-metric":
function monthsUntil(year,month,day,hour=0){
const trg=new Date(year,month-1,day,hour,0,0),
now=new Date(), nxt=new Date();
nxt.setFullYear(nxt.getFullYear()+1);
return (12*(trg-now)/(nxt-now)).toFixed(4);
}
console.log(monthsUntil(2022,12,1,16))
So I'm having trouble finding a solution to this online, and if there's one thing I hate; it's working with dates.
I need to be able to calculate a person's age in months and days. So if they were born July 3rd, 2020 I need something like 2 months, 21 days.
I have the code for the months here: return dayjs(dayjs()).diff(value, 'month'); where value is the date, but am struggling to think of a way to get those days to be accurate.
Anything would be great! Thank you.
I would suggest that you subtract the the numbers that represent the days in your dates from one another and take the absolute value.
In your example, with the dates July 3rd, 2020 and September 24th, 2020, this would mean doing 3-24 = -21, which would be 21 after taking the absolute value.
Note that your problem is sort of ill-posed. It doesn't really make sense to give someone's age in months, as the amount of days change in a given month. But what you can do is define that x months later just means changing the value of the months in a date. I.e., two months after July 3rd would be September 3rd. This way you can just take whatever difference remains and use this as number of days, as shown above.
I was looking into a problem in a web app where the displayed number of days between two dates was one day out in certain circumstances.
I then narrowed this down to being caused by one particular day, namely the 28th of November 2018. If any date pair passed through this day, the number of days is no longer an integer.
Further refining my search I found the reason was that the function was reporting a time of 25 hours for the period from the 28th to the 29th of November, 2018.
var fromDate = new Date(2018,09,28).getTime()
var toDate = new Date(2018,09,29).getTime()
var hours = (toDate - fromDate) / (1000 * 3600)
Can anyone explain this behaviour?
As said in the comments, in, for example, Europe, Daylight Savings Time ends on the 28th of October, 2 AM becomes 1 AM if I'm not mistaken, resulting in a day that takes 25 hours.
https://www.timeanddate.com/time/dst/2017.html
I am using the following in moment.js to convert seconds to Days Hours Minutes Seconds format
moment().startOf('year').seconds(1209600).format('DD HH:mm:ss')
But instead of getting 14 00:00:00, I am getting 15 00:00:00
What am I missing here?
1209600 seconds is 14 days, so because the first day of the year is day 01 00:00:00, if you add 14 days you get 15 00:00:00.
You don't say exactly what you're trying to do, but what you're getting is the right answer for "what's the date/time for 1209600 seconds into the year."
You're attempting to work with the concept of duration, but you're using the calendar to do it. This isn't a good idea for several reasons. As others pointed out, the calendar starts on the 1st, which is throwing you off. But also, you could have local time zone discontinuities affect your results, such as if your duration went far enough into the year to be caught by the spring-forward daylight saving time transition.
If you want to use Moment to work with durations, there is a separate API for that:
var d = moment.duration(1209600, 'seconds');
var h = d.hours();
var m = d.minutes();
var s = d.seconds();
There is currently not a format method built-in for durations, so you'd have to assemble these into a string yourself, applying zero-padding where necessary. However, there is the moment-duration-format third-party plugin, which would let you do it like this:
moment.duration(1209600, 'seconds').format('DD HH:mm:ss')
moment().startOf('year'); // set to January 1st, 12:00 am this year
So, startOf('year') method set moment starting point to 1st January of current year from 12.00 AM
, which is start of the day. and you are adding 14 days on top of that. But as the initial date started at 12.00 AM, its still a whole day (ends at 11.50 PM) which adds one additional day in final result.
Given a start date, and a number of days, I need to display the end date = start date + number of days.
So I did something like this:
var endDate=new Date(startDate.getTime()+ONE_DAY);
Everything works fine, except that for 25 and 26 October gives one day less.
Ex.:
2014-01-01 + 2 days = 2014-01-03
2014-10-25 + 2 days = 2014-10-26 (here is the case I need to treat).
This difference appear because of the clock going back 1 hour. Practically 2014-10-27 00:00:00 becomes 2014-10-26 23:00:00.
A simple solution would be to compute this at another hour (example 3 AM). But I want to just display a note when this happens.
For example, if user inputs 2014-10-25, I show a popup saying [something].
Now here is the real problem... I can't seem to find any algorithm that says when clocks goes back in year X.
Example... in 2014 the day is 26 October. In 2016 is 30 October (https://www.gov.uk/when-do-the-clocks-change). Why? This date looks random to be, but I don't think it is. So... when does clock go back/forward?
EDIT: All answers/comments are helpful related to how to fix the problem. But... I already passed that stage. Now I only have an itch about "how on earth are the days when clock is changed computed?".
To find the difference between two dates in whole days, create Date objects, subtract one from the other, then divide by the milliseconds in one day and round. The remainder will only be out by 1 hour for daylight saving so will round to the right value.
You may also need a small function to convert strings to Dates:
// Return Date given ISO date as yyyy-mm-dd
function parseISODate(ds) {
var d = ds.split(/\D/);
return new Date(d[0], --d[1], d[2]);
}
Get the difference in days:
function dateDiff(d0, d1) {
return Math.round((d1 - d0)/8.64e7);
}
// 297
console.log(dateDiff(parseISODate('2014-01-01'), parseISODate('2014-10-25')));
If you want to add days to a date, do something like:
// Add 2 days to 2014-10-25
var d = new Date(2014, 9, 25);
d.setDate(d.getDate() + 2);
console.log(d); // 2014-10-27
The built–in Date object takes account of daylight saving (thought there are bugs in some browsers).
I prefer adding days this way:
var startDate = //someDate;
var endDate = new Date(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()+1);
This way you don't have to worry about the days in the calendar.
This code add 1 day, if you want to add more, change the startDate.getDate()+1 for startDate.getDate()+NUMBER_OF_DAYS it works fine even if you are on the last day of month i.e. October 31th.
But maybe you can use #RobG solution which is more elegant than mine