Moment js date time comparison
I believe you are looking for the query functions, isBefore
, isSame
, and isAfter
.
But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff
. For example:
moment().diff(date_time, 'minutes')
A few other things:
There's an error in the first line:
var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
That's not going to work. I think you meant:
var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
Of course, you might as well:
var date_time = '2013-03-24T10:15:20:12Z';
You're using:
.tz('UTC')
incorrectly..tz
belongs to moment-timezone. You don't need to use that unless you're working with other time zones, likeAmerica/Los_Angeles
.If you want to parse a value as UTC, then use:
moment.utc(theStringToParse)
Or, if you want to parse a local value and convert it to UTC, then use:
moment(theStringToParse).utc()
Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.
You seem to be getting the "now" instance by
moment(new Date())
. You can instead just usemoment()
.
Updated
Based on your edit, I think you can just do this:
var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');
Or, if you would like to ensure that your fields are validated to be in the correct format:
var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');
How to Compare Date time in moment js
Yes it will validate date along with the time. Here is the code which shows the 1 second difference between two dates.
const out = document.getElementById('output');
const today = moment();
var afterToday;
setTimeout(()=>{
afterToday = moment();
}, 1000)
setTimeout(()=>{
//const diff = afterToday.isAfter(today);
const diff = today.isAfter(afterToday);
out.innerText = diff;
}, 2000)
To see it in action take a look here.
date comparison moment js
There are two issues there:
You're expecting
moment
to guess the format of your dates, but it can't do that reliably. Always provide a format string if your string isn't in a RFC2822 or ISO-8601 format.moment
itself warns you about doing that in the dev version of the library:Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/
<
cannot be used to meaningfully compare objects. If you want to know if a date is before another date, use theisBefore
method.
For example:
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Comparing date and time with moment js
Combine the date and time strings, and parse as one full date-time string.
const endDate = '04/13/2022';
const endTime = '22:00';
const date = moment(`${endDate} ${endTime}`, 'MM/DD/YYYY HH:mm');
console.log(date.isBefore(moment())); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
Comparing 2 dates with momentJS
For anyone who is interested, the code I posted in my question was changing the day/hour but was setting the year to 2015 which meant that it was always in the past.
To fix I separated out the Day and the Hour and set to moment. Then compared that with now. e.g.
moment().set({"Day": "Friday", "Hour": "17"}).isBefore(moment())
Comparing time with MomentJS
To use ==
or <
or >
you need to convert the moment to a number. To do that use .valueOf()
. For example:
today.valueOf() < moment('03:00', 'hh:mm').valueOf()
However, moment.js also provides methods that are more readable:
today.isBefore(moment('03:00', 'hh:mm'))
You can use .isBefore()
, .isAfter()
, .isSame()
, .isSameOrBefore()
etc. Read the documentation for more info: http://momentjs.com/docs/#/query/
Compare if 2 dates are the same in javascript
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>
How to compare only date in moment.js
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.
Related Topics
Jquery.Inarray(), How to Use It Right
React Hooks Usestate() with Object
Moment Js Date Time Comparison
Get Functions (Methods) of a Class
Removeeventlistener on Anonymous Functions in JavaScript
Keyboard Shortcuts with Jquery
JavaScript Convert Hsb/Hsv Color to Rgb Accurately
Clone Object Without Reference JavaScript
How to Get the (X, Y) Pixel Coordinates of the Caret in Text Boxes
How to Perform Case-Insensitive Sorting Array of String in JavaScript
Random Number, Which Is Not Equal to the Previous Number
How to Duplicate Object Properties in Another Object
Does JavaScript Have the Interface Type (Such as Java's 'Interface')
Generate PDF from HTML Using PDFmake in Angularjs
How Does Asynchronous JavaScript Execution Happen? and When Not to Use Return Statement