tpcordeiro
tpcordeiro

Reputation: 443

Strange behavior of Date/Calendar

I just want to create a method that sets the Date to time "23:59:59.999" of the same day. So I made this:

public static Date date235959(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR, 23);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    c.set(Calendar.MILLISECOND, 999);
    //c.set(Calendar.AM_PM, Calendar.PM);

    return c.getTime();
}

When I run:

Date d = new Date();
d=date235959(d);
System.out.println(d.toString());
d=date235959(d);
System.out.println(d.toString());

I expected
Tue Sep 17 23:59:59 BRT 2013
Tue Sep 17 23:59:59 BRT 2013

But the output was
Tue Sep 17 23:59:59 BRT 2013
Wed Sep 18 11:59:59 BRT 2013

Why is that happened and how can I fix it?

Upvotes: 3

Views: 322

Answers (2)

Macchiatow
Macchiatow

Reputation: 607

Use JodaTime instead of Java Calendar. It is the way more user friendly.

  • All Joda Time date/time objects are built on top of a long timestamp, so it is cheap to create those objects from a long.

  • In Joda Time ver 2.1 creating a date/time object from date/time components (year, month, day, hour, min, sec) is ~3.5 time slower than the same operation for JDK GregorianCalendar. Date components addition/subtraction is 3.5 times slower in Joda Time rather than in GregorianCalendar. On the contrary, time components operations are about the same 3.5 times faster than GregorianCalendar implementation.

  • Date/time parsing is working at about the same speed as in JDK SimpleDateFormat. The advantage of Joda parsing is that creating a parser – DateTimeFormatter object is extremely cheap, unlike an expensive SimpleDateFormat, so you don’t have to cache parsers anymore.

http://java-performance.info/joda-time-performance/

Upvotes: 0

Aleksandr M
Aleksandr M

Reputation: 24406

The Calendar.HOUR is used for the 12-hour clock, use Calendar.HOUR_OF_DAY instead or put correct value for 12-hour clock: c.set(Calendar.HOUR, 11);

Upvotes: 5

Related Questions