Moment js date time comparison

JavascriptJqueryDatetimeMomentjs

Javascript Problem Overview


I'm using moment.js to format my date time, here I have two date values, and I want to achieve a particular function when one date is greater than the other. I read most of their docs, but didn't find the function to achieve this. I know it will be there.

This is my code:

var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
var d = moment(date_time).tz('UTC'); // first date 

var now = new Date(),
    dnow = moment(now).tz('UTC'),
    snow = dnow.minute() % 15,
    diffnow = 15 - snow,
    tonow = moment(dnow).add('minute', diffnow),
    ahead30now = moment(tonow).add('minute', 30);

if (d > ahead30now) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {
    
}

Edit

var date_time = req.body.date + 'T' + req.body.time + req.body.timezone; // 2014-03-24T01:15:000
var utc_input_time = moment(date_time).utc(); // 2014-03-24T01:15:000
console.log('utc converted date_time', moment(date_time).utc().format("YYYY-MM-DDTHH:mm:SSS"));
var isafter = moment(utc_input_time).isAfter(moment('2014-03-24T01:14:000')); // true
if(isafter === true){
    console.log('is after true');
} else {
    console.log('is after is false');
}

Here, I am comparing two dates i.e. 2014-03-24T01:15:000 > 2014-03-24T01:14:000, expecting that the first one is greater than the second one, but it always goes to the else condition. I don't know why?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

You should be able to compare them directly.

var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}

$(document).ready(function() {
  
  $('.compare').click(function(e) {
  
    var date = $('#date').val();
  
    var now = moment();
    var then = moment(date);
  
    if (now > then) {
      $('.result').text('Date is past');
    } else {
      $('.result').text('Date is future');
    }

  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>



<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">
<button class="compare">Compare date to current date</button>
<br>
<div class="result"></div>

Solution 3 - Javascript

It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore, isAfter, isSameOrBefore, isSameOrAfter, isBetween

So instead of 2014-03-24T01:14:000, your datetime should be either:

> 2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z

otherwise you may receive the following deprecation warning and the condition will evaluate to false:

> 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 and will be removed in an upcoming major > release. Please refer to > http://momentjs.com/guides/#/warnings/js-date/ for more info.

// https://momentjs.com/docs/#/query/

const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));

const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));

const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));

console.log(`Date is After: ${dateIsAfter}`);
console.log(`Date is Same: ${dateIsSame}`);
console.log(`Date is Before: ${dateIsBefore}`);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"
></script>

Solution 4 - Javascript

Jsfiddle: http://jsfiddle.net/guhokemk/1/

 function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("11/07/2015", "10/07/2015"));

The method returns 1 if dateTimeA is greater than dateTimeB

The method returns 0 if dateTimeA equals dateTimeB

The method returns -1 if dateTimeA is less than dateTimeB

Solution 5 - Javascript

for date-time comparison, you can use valueOf function of the moment which provides milliseconds of the date-time, which is best for comparison:

const date1 = moment('01-02-2020', 'DD-MM-YYYY').valueOf()
const date2 = moment('11-11-2012', 'DD-MM-YYYY').valueOf()

// console.log((date1 > date2 ? 'date1' : 'date2') + " is greater..."  )

if (date1 > date2) {
  console.log("date1 is greater...")
} else {
  console.log("date2 is greater...")
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Solution 6 - Javascript

moment(d).isAfter(ahead30now); // true

http://momentjs.com/docs/#/query/is-after/

if (moment(d).isAfter(ahead30now)) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {

}

Solution 7 - Javascript

pass date to moment like this it will compare and give result. if you dont want format remove it

moment(Date1).format("YYYY-MM-DD") > moment(Date2).format("YYYY-MM-DD")

Solution 8 - Javascript

var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");

var isAfter = moment(startDate).isAfter(endDate);

if (isAfter) {
    window.showErrorMessage("Error Message");
    $(elements.endDate).focus();
    return false;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDibishView Question on Stackoverflow
Solution 1 - JavascriptMatt Johnson-PintView Answer on Stackoverflow
Solution 2 - JavascriptryanwinchesterView Answer on Stackoverflow
Solution 3 - JavascriptJSON C11View Answer on Stackoverflow
Solution 4 - JavascriptRazan PaulView Answer on Stackoverflow
Solution 5 - JavascriptTyagiView Answer on Stackoverflow
Solution 6 - JavascriptTV-C-1-5View Answer on Stackoverflow
Solution 7 - Javascriptvijay kumarView Answer on Stackoverflow
Solution 8 - JavascriptisaacView Answer on Stackoverflow