Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 2 dates with momentJS

I am trying to compare a DAY/TIME e.g. Monday 09:00:00 with the current time to see if I am past that point in the week. e.g. If it is now 05:00:00 on Monday it should return true however it is returning false everytime

var dayTime = Moment("Wednesday 17:00:00", "dddd HH:mm:ss");
var now = Moment(Moment.now(), "dddd HH:mm:ss");
console.log(Moment.utc(dayTime).isBefore(now)); //returns false all the time

I found the following similar questions but it didn't seem to fix the issue after formatting the time.

Comparing two times with Moment JS

When I replace the moment.now() with a string such as "Wednesday 17:00:00" it returns the expected result.

Any idea what I need to do to moment.now() in order for this to work correctly?

like image 712
Geraint Avatar asked Jun 13 '16 21:06

Geraint


People also ask

Should you still use MomentJS?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.

What is MomentJS used for?

MomentJS is a JavaScript library which helps is parsing, validating, manipulating and displaying date/time in JavaScript in a very easy way. This chapter will provide an overview of MomentJS and discusses its features in detail. Moment JS allows displaying of date as per localization and in human readable format.


2 Answers

Moment.now can be used as an extension point, but it's really not a public API. To get the current time in momentjs you just call moment(). Note that all moment calls use lowercase moment.

To see if your date and time is before the current time, you would just call:

moment('01/01/2016', 'MM/DD/YYYY').isBefore(moment())

You would replace the date and format in question with your own.

I see that you have a date format that includes only day of week and time. Moment will parse this, but be aware that the behavior might not be what you expect. When I parse your date, I get Wednesday December 30, 2015. Exactly what day this lands on will vary by locale. In any case, I doubt that it is what you want. If at all possible, I would get year, month, and day.

If you would like to instead set the moment to Wednesday this week, set the day on the moment using .day(). For instance:

moment().day(3).format()
"2016-06-15T20:19:55-05:00"
like image 167
Maggie Pint Avatar answered Oct 01 '22 10:10

Maggie Pint


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())
like image 23
Geraint Avatar answered Oct 01 '22 08:10

Geraint