Moment js date time comparison
Asked Answered
T

10

538

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?

Transfigure answered 24/3, 2014 at 4:1 Comment(0)
H
702

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');
Hernandes answered 24/3, 2014 at 4:29 Comment(1)
you can just use plain comparator: moment('2014-01-02') > moment('2024-01-01') I see now, there is an answer for that. my bad.Ketene
S
320

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>
Surd answered 24/3, 2014 at 4:19 Comment(3)
I feel like it's worth explaining that this works because javascript coerces objects to primitives via Object.prototype.valueOf which is overridden in the moment prototype to return an epoch timestamp as a number. So this is similar to now.format('x') > date.format('x').Tippet
no its not working... here is what i tried . // newDate is higher then now's date...so it prints fail in both greaterthen and lessthen conditions const resDate = res.url.expiryDate; const newDate = moment(resDate); var now = moment().format("DD/MM/YYYY"); if (now<newDate) { console.log("success"); } else { console.log("fail") }Rosanarosane
@Rosanarosane moment().format("DD/MM/YYYY") will return a string and then you are comparing alphabetically and then December 1st would come before January 2, because you are leading with days, too. Don't use format() if you want to compare the moment objcts directly.Surd
H
53

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>
Helvetia answered 31/3, 2018 at 23:37 Comment(0)
H
36

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

Humanitarian answered 5/7, 2016 at 1:55 Comment(0)
D
27

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>
Dustidustie answered 20/2, 2020 at 20:4 Comment(0)
M
14
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 {

}
Maccarone answered 17/9, 2017 at 21:49 Comment(0)
G
10
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;
}
Grimy answered 18/4, 2019 at 7:26 Comment(0)
A
7

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")
Alcoholism answered 7/6, 2017 at 11:19 Comment(3)
Be careful this is nothing but comparing two stringPentapody
@PranoySarkar can you please tell me why we need to be more careful?Hawking
I think the point was that you need to be careful here because you are really comparing strings, not dates when using .format. It works in this case because it's year, then month, then day ("YYYY-MM-DD"). However, if you had a format of "MM-DD-YYYY" or "DD-MM-YYYY", it may not do what you intend (check if one date is greater than another date). For example. "01-01-2021" > "12-12-1990" will return false because it starts the comparison at the first character, and 0 comes before 1. So just be careful that it's formatted in a way that would work in all instances.Kassab
C
0
  • Check two dates equal or not using moment js.
  • I used granularity => 'D' for check date only without time.

this command working fine for me.

moment(date1).isSame(moment(date2), 'D') 
Chrismatory answered 5/9, 2023 at 22:56 Comment(0)
K
-1

say if you want to disable past dates in date picker the following code will surely going to help you disabledDate={(current) => { return ( current && current.format("YYYY-MM-DD") < moment().format("YYYY-MM-DD") ); }}

Kano answered 17/11, 2022 at 10:58 Comment(1)
A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation.Adopted

© 2022 - 2024 — McMap. All rights reserved.