[javascript] Moment js date time comparison

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?

This question is related to javascript jquery datetime momentjs

The answer is


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;
}

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.

_x000D_
_x000D_
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
_x000D_
_x000D_


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")

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


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
}

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  _x000D_
  $('.compare').click(function(e) {_x000D_
  _x000D_
    var date = $('#date').val();_x000D_
  _x000D_
    var now = moment();_x000D_
    var then = moment(date);_x000D_
  _x000D_
    if (now > then) {_x000D_
      $('.result').text('Date is past');_x000D_
    } else {_x000D_
      $('.result').text('Date is future');_x000D_
    }_x000D_
_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">_x000D_
<button class="compare">Compare date to current date</button>_x000D_
<br>_x000D_
<div class="result"></div>
_x000D_
_x000D_
_x000D_


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 {

}

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

_x000D_
_x000D_
let date1 = moment('01-02-2020','DD-MM-YYYY').valueOf()_x000D_
let date2 = moment('11-11-2012','DD-MM-YYYY').valueOf()_x000D_
_x000D_
//     alert((date1 > date2 ? 'date1' : 'date2') + " is greater..."  )_x000D_
_x000D_
if (date1 > date2) {_x000D_
   alert("date1 is greater..." )_x000D_
} else {_x000D_
   alert("date2 is greater..." )_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to momentjs

How to get am pm from the date time string using moment js Vuejs and Vue.set(), update array How to subtract one month using moment.js? Get timezone from users browser using moment(timezone).js Check if date is a valid one moment.js get current time in milliseconds? Deprecation warning in Moment.js - Not in a recognized ISO format Moment js get first and last day of current month Moment get current date Moment.js - How to convert date string into date?