1

I'm comparing two dates one is a general date and other is got from gregorian calendar.
when i tried to compare both dates it is giving result false,
Later i realized that it is due to time difference. So even both dates are same and times different i want it to return true or set date of the latter to default.ie,0

Eg: Start Date : Wed May 08 00:00:00 CAT 2013  
End Date : Wed May 08 00:40:30 CAT 2013    

I tried calender API, set(year,month,day,hour,minute,second); but setting year,month and day i don't know. Please help me this regard to fix it.

Mr.Chowdary
  • 3,389
  • 9
  • 42
  • 66
  • 1
    Possible duplicate of these questions: http://stackoverflow.com/questions/2517709/java-comparing-two-dates-to-see-if-they-are-in-the-same-day OR http://stackoverflow.com/questions/9474121/i-want-to-get-year-month-day-etc-from-java-date-to-compare-with-gregorian-calen – Gray Kemmey May 07 '13 at 22:51

3 Answers3

5

You can use simple java code to get date without time as below. This method will set time part for any date to 00:00:00

private Date getDateWithOutTime(Date targetDate) {
    Calendar newDate = Calendar.getInstance();
    newDate.setLenient(false);
    newDate.setTime(targetDate);
    newDate.set(Calendar.HOUR_OF_DAY, 0);
    newDate.set(Calendar.MINUTE,0);
    newDate.set(Calendar.SECOND,0);
    newDate.set(Calendar.MILLISECOND,0);

    return newDate.getTime();

}
sagar
  • 1,392
  • 1
  • 12
  • 19
  • It is possible that the change to the time might actually role the date back or forward a day. I'd, personally look at setting the time either 1 millisecond before or after midnight, but that's just me +1 – MadProgrammer May 07 '13 at 23:56
  • @MadProgrammer above code will not roll date, it will just set time for the date portion. – sagar May 07 '13 at 23:58
  • And based on the rules of the calendar it "might" roll the date - didn't say it was a high likely hood, just a possibility ;) - I'd be like trying to set the DAY_OF_MONTH to 31 when the calendar is set to February, the calendar will auto just... – MadProgrammer May 08 '13 at 00:01
  • @sagargondhale Thanks for your time with me.. It's working well.. – Mr.Chowdary May 08 '13 at 10:28
1

try

        Calendar cal = Calendar.getInstance();
        cal.set(2014,Calendar.JUNE,29,0,0,0);        
        date = cal.getTime();
Youans
  • 4,801
  • 1
  • 31
  • 57
  • 1
    Please indicate *why* this answers your question. This question was flagged because its main content is just code. – Maarten Bodewes Jun 23 '14 at 23:16
  • This solution is not valid, even risky, because it keeps the milliseconds part, so it won´t compare accurately against other "datetime" values – jpe Jan 02 '17 at 16:14
0

You can round millis to days and compare them, this will be faster than Calendar based version

    long t1 = date1.getTime() / 86400000 * 86400000;
    long t2 = date2.getTime() / 86400000 * 86400000;
    return Long.compare(t1, t2);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275