Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two isodates in mongo

If I have two ISODates such as:

Tue Sep 18 1984 00:00:00 GMT+0100 (CET) 

and

Sat Jun 21 2014 10:00:00 GMT+0100 (CET)

how do I get a difference between them using the mongo console? Specifically the difference in years?

they are from different collections so I can't use an aggregation for this.. :(

like image 357
ricardoespsanto Avatar asked Aug 23 '26 16:08

ricardoespsanto


1 Answers

ISODate() is just a convenient wrapper around a standard JavaScript Date object so you can use the standard Date methods or calculate the difference yourself (date values are stored in milliseconds):

> var date1 = ISODate("1984-09-18");
> var date2 = ISODate("2014-06-21");

> date2.getFullYear() - date1.getFullYear()
30

> var yearMS = 365 * 24 * 60 * 60 * 1000; // a year in milliseconds
> parseFloat((date2-date1)/yearMS).toFixed(2)
29.78
like image 83
Stennie Avatar answered Aug 26 '26 01:08

Stennie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!