2

I have a long data member that represents a date.
I cast it to a

 Date d = new Date(long);  

I want to now if a nother date has the same day. How do I do it? Thanks.
(For andrew)

Edit :

Found this solution

 SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
 return fmt.format(date1).equals(fmt.format(date2));

in here Comparing two java.util.Dates to see if they are in the same day looks nice

Community
  • 1
  • 1
Bick
  • 17,833
  • 52
  • 146
  • 251

5 Answers5

3

Well you can convert them both to calendar Objects and get the calendar objects day and compare that way.

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(LONG VALUE HERE);
int day = cal.get(Calendar.DAY_OF_MONTH);

Do the same thing with the other date, and compare the values.

edit: By the way, you are not casting the long to a date, you are just creating a Date object using a long.

RMT
  • 7,040
  • 4
  • 25
  • 37
  • I think instead of Calendar.DAY_OF_MONTH we should check Calendar.DAY_OF_YEAR because 15 of jun and 15 of july would be same so day of year is right one check -https://stackoverflow.com/a/2517824/4741746 – Sushant Gosavi Dec 01 '17 at 06:51
3

use the joda api.
http://joda-time.sourceforge.net/
Its a lot easier and better than the Calendar object route in java jdk

sethu
  • 8,181
  • 7
  • 39
  • 65
2

Use apache commons.

 DateUtils.isSameDay(date1, date2);
ziri
  • 513
  • 7
  • 18
1

To see if the dates are equal:

date_one.equals(date_two);

To see if just the day is equal, I usually chop the time off the date (setHours(0), setMinutes(0), etc.) and then use the .equals() method.

minichate
  • 1,914
  • 13
  • 17
1

Use java.util.Calendar for all comparison operations.

stemm
  • 5,960
  • 2
  • 34
  • 64