简体   繁体   中英

How to compare these two dates?

What's the best way to compare a Java date with Javascript date for greater than or less than comparison?

Java date format: 1985-01-01T00:00:00.000-06:00

Javascript date format: Tue Jan 29 1980 00:00:00 GMT-0600

Both Java and Javascript Date objects have a getTime method, that returns the number of milliseconds since the epoch. Ideally, you'd send the date from Java in that format rather than as a string.

Failing that, you could parse it in Javascript with something like this to convert it to a Date , and then compare to the other as normal (modern browsers will be able to handle ISO 8601 out of the box, but notably IE 8 or lower won't).

If you have two date objects, you can compare them directly:

var date0 = new Date(2012,0,1); // 1 Jan 2012
var date1 = new Date(2012,1,1); // 1 Feb 2012

if (date0 < date1)  { /* true */ }

Otherwise, if both dates are ISO8601 dates in the same time zone, you can compare them as strings:

var date0 = '2012-01-01T00:00:00.000';
var date1 = '2012-02-01T00:00:00.000';

if (date0 < date1)  { /* true */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM