Moment js date time comparison

I believe you are looking for the query functionsisBeforeisSame, 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 functiondiff. 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, like America/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 use moment().

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');

Leave a Comment