开发者

Dates comparisons in java

I would like开发者_运维问答 to compare a date to the current date. could you please tell me how to do that in java.


You can get the current date, with the current locale/timezone, by doing

Date now = new Date();

Then given another date, d, you can do:

if (d.equals(now))
or
if (d.after(now))
or
if (d.before(now))

etc.

If the date you have is provided to you as a String, use

java.text.SimpleDateFormat.java to convert it to a Date object.


Get the dates (however you get them, in the code below it is new Date()) and then use the getTime() to get the Unix time (offset from January 1, 1970, 00:00:00 GMT) to do the comparison

Date then = new Date();
...
Date now = new Date();

long thenInMilliseconds = then.getTime();
long nowInMilliseconds = now.getTime();

if(nowInMilliseconds [<, <=. ==, >=, >] thenInMilliseconds)

You can also use the compareTo method, or as is pointed out in another answer the before and after methods.

EDIT based on comment below:

To parse a date from a String you can use the SimpleDateFormat class (there are other ways too).

For example here is some code I am using for that:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = dateFormat.parse("2010-02-12T18:03:15Z");


Date d1 = new Date();
Date d2 = new Date();
int results = d1.compareTo(d2);

d1 and d2 should be initialised with the dates and can be compared

CompareTo is the method that helps you to find the difference between the dates.


With a java.util.Date it can be done with:

Date today = new Date();
today.equals(otherDate) / today.after(otherDate) / today.before(otherDate)

If you want a more precise calculation I would recommend that you don't use Date since many methods of it are deprecated. java.util.Calendar is better, with it the current date is accessed like this:

Calendar cal = Calendar.getInstance();

If you are comparing a Calendar with a Date, the comparison can be done like this:

Date date //your date
Calendar.getInstance().equals(date)/before(date)/after(date);

But you can also get the exact millisecond count:

long diff = Calendar.getTimeInMillis() - date.getTime();


Under the covers a Date is just a long number of milliseconds since 1 January 1970. You can get the long value using myDate.getTime(). To do Date comparisons you could just compare their long values this way. But as others have pointed out Date has some nice methods to make this clearer: equals(), before(), and after().

To convert a string to a Date, use SimpleDateFormat. See this tutorial.

I've recently started using the Joda-Time library, which is much, much easier to understand and work with than Java's Dates and Calendars.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜