get months difference between two dates javascript - javascript

I'm trying to compare two dates and get the number of months that exist between them, for which it uses the moment library and I get something like this:
var date1 = moment('2021-05-30');
var date2 = moment('2021-06-30');
var result = date2.diff(date1, 'months');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
however within my business model there will not always be exact dates like these: '2021-05-30' to '2021-06-30' Also in the cases that have '2021-06-1' to '2021-06-15' which are like 15 days apart, I already want it to take 1 month even though there is precisely no 30 days difference, or if I have the dates '2021-06-1' to '2021-07-15' which are approximately 45 days, it already took me about 2 months, so how can I control that? any ideas? It does not matter if it is with moment or another library, I hope your help thank you very much

You can pass third param to diff function.
var result = date2.diff(date1, 'months', true);
This will return the result as decimal. Then you can use Math.ceil function to get the desired result.
var result = Math.ceil(date2.diff(date1, 'months', true));

Related

Compare if 2 dates are the same in javascript

var beginningTime = moment('1635750314812', 'YYYY/MM/DD'); // Today date
var endTime = moment(undefined, 'YYYY/MM/DD') // Today date
console.log(beginningTime.isSame(endTime)); //expect true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I am using moment js to get if 2 date are the same using the above pattern. But now i get false instead of true. How to solve the issue?
Instead of formatting the beginningTime and endTime separately, you should take a look at the 'granularity' argument for isSame().
I made a few adjustments to your code for it to work, and also look cleaner.
var beginningTime = moment(1635750314812); // Today date (from timestamp)
var endTime = moment() // Today date
console.log(beginningTime.isSame(endTime, 'day')); //expect true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
It first simply creates a moment of your timestamp and a moment of right now, whenever now is.
Then it will compare the two moments with a granularity of a day, effectively checking if the day and everything bigger (month, year) is the same.

Error converting selected date - Angular 8

I am making a filter between two dates, Start date and End date, the filter works perfect, it brings the data but it does not bring the complete data and it is because when selecting the dates and converting them to the format, it converts them but one day remains.
This way I am converting the dates:
FiltrarPorFechas(incial, final) {
this.ListaUsuarios = [];
const IniDate = new Date(incial);
const EndDate = new Date(final);
}
associate an image with debug and conversion:
As shown in the image, the initial and final dates arrive at the method thus "2019-07-10" and "2019-07-31" but when I try to convert them it puts them one day less as shown in the image.
I have tried to use moment formatDate and it does not work, I do not understand why and I do not want to add one day.
Somebody could help me ?
You may be potentially having an issue with Timezone. You could reset the time to 00:00:00 either using moment.js or from a normal Date() object.
Now, since your aim is to compare the times, you can use the diff() available from moment.js to achieve this. Please find the sample code below
(function() {
initial = '2019-07-09';
initial_formatted = moment(new Date(`${initial} 00:00:00`));
final = '2019-07-31';
final_formatterd = moment(new Date(`${final} 00:00:00`));
console.log(initial_formatted.diff(final_formatterd, 'days'));
// moment(new Date(`${incial} 00:00:00`)).format('YYYY-MM-DD HH:mm:ss');
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
More info
Moment diff()
Date Object set() method

Moment.js diff wrong behaviour

I have a date and I want to substract today of this date. This is my example:
date.format('YYYY-MM-DD')
"2018-04-07"
moment().format('YYYY-MM-DD')
"2018-04-06"
date.diff(moment(), 'days')
0
The diff call returns 0 instead of 1. What is wrong here?
By default, moment#diff will truncate the result to zero decimal
places, returning an integer. If you want a floating point number,
pass true as the third argument. Before 2.0.0, moment#diff returned a
number rounded to the nearest integer, not a truncated number.
To see the full value, pass true as the third parameter:
now.diff(date, 'days', true)
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone. And compare with date
Use fromNow() function to understand why you are getting 0 instead of 1. It is very straight-forward.
Do like this :
moment(date).fromNow();
It will give you number of days passed if time is greater than 24 hours otherwise it will give to time in hours. e.g. 2 hours ago, 23 hours etc.
Below is example:
console.log(moment("2018-04-06", "YYYY-MM-DD").fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
So you can see it is returning 18 hours ago (as of now) which is less than 24hours i.e. 1 day.
I would suggest to use fromNow instead of diff to get exact difference.
Hope now it makes clear to you.
moment() returns a full moment including time, so it's doing a diff from today, including time, to midnight of the 7th of April, which isn't a full day.
I was also facing the same issue. So after a few research on StackOverflow and moment.js documentation I came up with this solution. Works perfectly for me.
const date1 = "2021-05-12T06:30:00.000Z"
const date2 = "2021-05-18T06:30:00.000Z"
const day1 = moment((moment(date1).format("YYYY-MM-DD")).split("-"))
const day2 = moment((moment(date2).format("YYYY-MM-DD")).split("-"))
const diff = day2.diff(day1,'days')

moment.js compare times with no dates

Is there an easy way in moment.js to compare times with no date attached?
It works when I have a full ISO object with date+time, but not when it's only a time.
For example, this basic code doesn't work because, I presume, it expects a date in the value:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore('12:00:00'));
I understand that I can just add an arbitrary date in there, but what is the elegant way to do this?
Update:
This works from the comment below by #RichardHamilton:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore( moment('12:00:00', "HH:mm:ss") ));

Display number of days between 2 datepicker dates?

I am looking to try and calculate the number of days between 2 datepicker fields and display that value in an input field. I have searched a lot of different methods but can't seem to get any to work. I am using boostrap-datepicker.js
I have created a JS fiddle here http://jsfiddle.net/KLpq7/201/ so you can see my effort so far
My JS Is as follows
function days() {
var a = $("#datepicker_start").datepicker('getDate').getTime(),
b = $("#datepicker_end").datepicker('getDate').getTime(),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
$("#totaldays").val(diffDays)
}
$('.datepicker')
.datepicker({format: 'DD, dd.mm.yyyy'})
.on('changeDate', function(ev){
$(this).datepicker('hide').blur();
});
In the first part I am trying to achieve this, but it is not working!
Looking for some help...
I have modified your jsfiddle that correctly calculates the differences. One think I noticed is that you use the dd/mm/yyyy format and by default JS wants the dates as mm/dd/yyyy. It is best if you handle it the 'American' way for date difference calculations, but if you must use the 'correct' style of dd/mm/yyyy then I would recommend taking a look at the Globalize library.
function DateDiff(var date1, var date2) {
return date1 - date2;
}
Should work if you pass in two Date objects in Javascript. The result returned will be the number of milliseconds between the two, which can be quite easily converted to days or hours or weeks, etc.

Categories