Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates using Java [duplicate]

Tags:

java

datetime

I have a date with the format 2012-02-02(yyyy-MM-dd).

For example if todays date is 2012-02-02 i need to add one and a half days to it which would make it 2012-02-03 06:00:00.0.

And if i have a number of dates of the following format 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) , i need to compare if all these dates are less than,greater than or equal to the date to which one and a half days were added above.

The comparison should also take care of the hours while comparing if the dates are less than,greater than or equal or equal to the other date and time.

How do i achieve the same.

like image 799
gautam vegeta Avatar asked Feb 03 '12 03:02

gautam vegeta


1 Answers

Simple arithmetic approach (faster)

  1. Parse the date using SimpleDateFormat that creates a Date object
  2. Use Date.getTime() to return the UTC value in long
  3. Convert 1 and half days to millis (1.5 Days = 129600000 Milliseconds) and add it to previous step
  4. Use >, < and == or after(), before() and equals() if you want to use Date object itself

API approach (slower)

  1. Use Calendar
  2. add(...) method for adding 1 and half day
  3. use before(), after() and equals() methods of Calendar
like image 164
Aravind Yarram Avatar answered Sep 25 '22 11:09

Aravind Yarram