Check for same day between Two dates

S

sriram

Hi All
Lets say I have 2 dates
Date d1 = new Date(2003,11,10,01,20);
Date d2 = new Date(2003,11,10,09,20);
They repesent 2 different times on the same day. Lets
say I want to know if the dates d1,d2 represent same day(immaterial of
time), I think one way of doing it is using simpledateformat
(converting this dates to strings and checking whether they are
equal). I am curious to know if there is any other effecient way.

Thanks
sriram
 
F

Fredrik Lindner

java.util.Calendar is an option. They have methods to retreive year, day
month etc as ints, which can be compared.

sample code:
public boolean sameDay(Calendar c1, Calendar c2) {
return (
c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR) ) &&
( c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) );
}
 
J

jock

sriram said:
Hi All
Lets say I have 2 dates
Date d1 = new Date(2003,11,10,01,20);
Date d2 = new Date(2003,11,10,09,20);
They repesent 2 different times on the same day. Lets
say I want to know if the dates d1,d2 represent same day(immaterial of
time), I think one way of doing it is using simpledateformat
(converting this dates to strings and checking whether they are
equal). I am curious to know if there is any other effecient way.

Thanks
sriram


Have a look to GregoriaCalendar class
 
A

Anton Spaans

Hi Sriram

Use the Calendar class (GregorianCalendar) to do so.
- Create an instance of Calendar (GregorianCalendar).
- Do setTime(d1) and then do set(HOUR, 0) and set(MINUTE, 0)
- Then do getTime(); returns a Date d1_dayonly
- Do setTime(d2) and then do set(HOUR, 0) and set(MINUTE, 0)
- Then do getTime(); returns a Date d2_dayonly.

Then you can use the method d1_dayonly.equals(d2_dayonly) to check for
equality.

-- Anton.
 
R

Roedy Green

Lets say I have 2 dates
Date d1 = new Date(2003,11,10,01,20);
Date d2 = new Date(2003,11,10,09,20);
They repesent 2 different times on the same day. Lets
say I want to know if the dates d1,d2 represent same day(immaterial of
time), I think one way of doing it is using simpledateformat

The question is more complicated than it first appears because of
timezones.

You want to treat the 24 hours known as Christmas in Hong Kong as
equivalent to the 24 hours known as Christmas in Coos Bay Oregon.

Best to convert to an ordinal day number.

See http://mindprod.com/jgloss/bigdate.html

for code.
 
S

sriram

Hi jock
I hope I did not miss anything but are you talking of any
method in Gregorian Calendar class which can do the check

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top