Moment js date time comparison

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Moment js date time comparison



I'm using moment.js to format my date time, here I have two date value, 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?


2014-03-24T01:15:000 > 2014-03-24T01:14:000




7 Answers
7



I believe you are looking for the query functions, isBefore, isSame, and isAfter.


isBefore


isSame


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:


diff


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.


.tz('UTC')


.tz


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().


moment(new Date())


moment()



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





Thanks for your valuable comments. I have edited my code to include your comments but not getting the difference correctly. Can u please check my edited code
– Dibish
Mar 24 '14 at 8:36





See updated answer. Also watch the number of digits in the seconds field. And is req.body.timezone ever anything other than Z? If so, what?
– Matt Johnson
Mar 24 '14 at 16:22


req.body.timezone


Z





Thank you so much for your edited code, i have almost reached there.. In my case i have that time zone number from user side eg date_time = 2014-03-25T23:10+5:30, when i use moment(date_time).utc() some time i got Invalid date
– Dibish
Mar 25 '14 at 4:26





When i put +05:30 it works great. Once again thank you so much for your kindness
– Dibish
Mar 25 '14 at 4:35





.isSame() is exactly what I was looking for. Somehow missed it in the docs before.
– Will Strohl
Oct 31 '15 at 19:42



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>





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').
– tandrewnichols
Sep 20 '17 at 17:29


Object.prototype.valueOf


now.format('x') > date.format('x')



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





function compare1(dateTimeA, dateTimeB) return moment(dateTimeA, 'MM/DD/YYYY').diff(dateTimeB, 'MM/DD/YYYY');
– Shamseer
Aug 21 '17 at 21:52



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



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


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>


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




I have to do this in my case, when user opens a quotation from transaction history if the quotation start date is less than current date I needed to show the current date as start date.


var startDate = "20/05/2018";

var date1 = moment().format("YYYY-MM-DD");
var date2 = moment(startDate).format("YYYY-MM-DD");

// and i checked with if statement

if(date1 > date2) // if startDate is less than today
startDate = date1;
else // if startDate is greater than today




NOTE : for me it needed to convert both dates into same format and I used "YYYY-MM-DD".






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard