Compare if 2 dates are the same in javascript - 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.

Related

Why does my momentjs issameorafter() not functioning properly [duplicate]

I am new to moment.js. I have a date object and it has some time associated with it. I just want to check if that date is greater than or equal to today's date, excluding the time when comparing.
var dateToCompare = 2015-04-06T18:30:00.000Z
I just want to check if dateToCompare is equal or greater than today's date.
I have checked isSame of moment.js, but it seems to take string and only the date part. But I do not want to convert my date to string or manipulate it further. Because I am worried that javascript may do something unexpected when converting that date to string(like adding the offset or dst,etc), or may be I am wrong.
Sample isSame() from docs
moment('2010-10-20').isSame('2010-10-20');
Also I am looking for something like isSame() and isAfter() combined as one statement.
I need to compare using moment.js only.Please do not suggest plain javascript date comparison.
The docs are pretty clear that you pass in a second parameter to specify granularity.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
For your case you would pass 'day' as the second parameter.
Meanwhile you can use the isSameOrAfter method:
moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');
Docs: https://momentjs.com/docs/#/query/is-same-or-after/
In my case i did following code for compare 2 dates may it will help you ...
var date1 = "2010-10-20";
var date2 = "2010-10-20";
var time1 = moment(date1).format('YYYY-MM-DD');
var time2 = moment(date2).format('YYYY-MM-DD');
if(time2 > time1){
console.log('date2 is Greter than date1');
}else if(time2 > time1){
console.log('date2 is Less than date1');
}else{
console.log('Both date are same');
}
<script src="https://momentjs.com/downloads/moment.js"></script>
You could use startOf('day') method to compare just the date
Example :
var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());
dateToCompare.startOf('day').isSame(today.startOf('day'));
moment('2022-01-07').isAfter(moment().format('YYYY-MM-DD'), 'day');
checking
2022-01-07 this with current date
if current date is beyond 6th Jan 2022, it returns false!
For checking one date is after another by using isAfter() method.
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
For checking one date is before another by using isBefore() method.
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
For checking one date is same as another by using isSame() method.
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
moment('date').toDate().getTime() > moment()

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

How to compare only date in moment.js

I am new to moment.js. I have a date object and it has some time associated with it. I just want to check if that date is greater than or equal to today's date, excluding the time when comparing.
var dateToCompare = 2015-04-06T18:30:00.000Z
I just want to check if dateToCompare is equal or greater than today's date.
I have checked isSame of moment.js, but it seems to take string and only the date part. But I do not want to convert my date to string or manipulate it further. Because I am worried that javascript may do something unexpected when converting that date to string(like adding the offset or dst,etc), or may be I am wrong.
Sample isSame() from docs
moment('2010-10-20').isSame('2010-10-20');
Also I am looking for something like isSame() and isAfter() combined as one statement.
I need to compare using moment.js only.Please do not suggest plain javascript date comparison.
The docs are pretty clear that you pass in a second parameter to specify granularity.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
For your case you would pass 'day' as the second parameter.
Meanwhile you can use the isSameOrAfter method:
moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');
Docs: https://momentjs.com/docs/#/query/is-same-or-after/
In my case i did following code for compare 2 dates may it will help you ...
var date1 = "2010-10-20";
var date2 = "2010-10-20";
var time1 = moment(date1).format('YYYY-MM-DD');
var time2 = moment(date2).format('YYYY-MM-DD');
if(time2 > time1){
console.log('date2 is Greter than date1');
}else if(time2 > time1){
console.log('date2 is Less than date1');
}else{
console.log('Both date are same');
}
<script src="https://momentjs.com/downloads/moment.js"></script>
You could use startOf('day') method to compare just the date
Example :
var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());
dateToCompare.startOf('day').isSame(today.startOf('day'));
moment('2022-01-07').isAfter(moment().format('YYYY-MM-DD'), 'day');
checking
2022-01-07 this with current date
if current date is beyond 6th Jan 2022, it returns false!
For checking one date is after another by using isAfter() method.
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
For checking one date is before another by using isBefore() method.
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
For checking one date is same as another by using isSame() method.
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
moment('date').toDate().getTime() > moment()

How to get time using Moment JS

I've two javascript variables: startDate and endDate. I want to store the current time(unix timestamp in ms) to endDate and timestamp of 24 hours before in startDate. I'll use this two variables to query the records for last 1 day. How can I do that using moment JS?
Have you looked at the website yet? It's full of examples - http://momentjs.com/ I think what you are trying to do is as simple as
var startDate = moment(endDate).subtract(1, 'days');
Following your question more literally, you can do this:
var endDate = moment(); //the current time
Or, you can just ignore the endDate part of this problem and go straight to startDate with
var startDate = moment().subtract(1, 'days'); //one day before the current time
Finally, if you need to format it a certain way, you can apply a formatting rule such as:
moment().subtract(1,'days').format('YYYY-MM-DD h:mm:ss a')
Use format without an argument and it gives you ISO 8601 format
moment().subtract(1,'days').format() //eg: "2015-04-04T01:53:26-05:00"
This worked for me although I have never found it in the docs. Should have been published but it works.
Try:
moment(currentTime).format("hh:mm"));or
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));
For those who are looking for a way to get timestamp, just do it:
moment().valueOf()
I think what you are looking for is something like
moment(endDate).unix()
which returns something like:
1435161240
You can even calculate the time from now using
moment(endDate).fromNow()
which returns something like:
"2 days ago"
You can directly call function momentInstance.valueOf(), it will return numeric value of time similar to date.getTime() in native java script.

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
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.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Categories