user1091524
user1091524

Reputation: 865

Calendar.setTime sets the wrong date

The code below sets the date to midnight on 7 June 2015. Why? My time zone is UTC-07:00

Greg

           Calendar HuntStart = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy K:mm a", Locale.US);
            try {
                HuntStart.setTime(sdf.parse("6/6/2015 12:00 PM"));//AllLists.get(position).HuntStart));
            }
            catch (ParseException ex) {

            }

Upvotes: 3

Views: 1728

Answers (3)

davidxxx
davidxxx

Reputation: 131316

The problem comes form the hour letter you are using in your SimpleDateFormat constructor.

See the SimpleDateFormat JavaDoc SimpleDateFormat javaDoc :

K Hour in am/pm (0-11)
h Hour in am/pm (1-12)

You are using the letter K and the javadoc says that this option should be used with hour (0-11) so that you use 12 in your String. I didn't look in the implementation of the class, but it's with no doubt a side-effect. You overlap the hour range allowed, so you go into the next day. It's pitty that the constructor be so permissive. An IllegalArgumentException or like would be useful.

To conclude, you have 2 solutions.

if you want use the 12 hour as source String for parsing, your should use the h letter pattern in your constructor. Like that :

    SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy h:mm a", Locale.US);

If you want to keep your hour pattern K, your should not use a String instance with 12 but 0 as input for the parse method Like that :

    huntStart.setTime(sdf.parse("06/06/2015 00:00 PM"));// AllLists.get(position).HuntStart));

Upvotes: 3

user1091524
user1091524

Reputation: 865

Gave up on Java Calendar and switched to Joda Time. The code below returns 2015-06-06T12:00:00.000-07:00 for HuntStart, as expected.

            DateTime HuntStart = new DateTime();
            DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy h:mm a");
            HuntStart = fmt.parseDateTime("6/6/2015 12:00 PM");

Upvotes: 1

Saptak Niyogi
Saptak Niyogi

Reputation: 338

Use the following code to update the calendar object instead of SimpleDateFormat

HuntStart.set(Calendar.MONTH,Calendar.JUNE);
HuntStart.set(Calendar.DAY_OF_MONTH,6);
HuntStart.set(Calendar.YEAR,2015);
HuntStart.set(Calendar.HOUR,12);
HuntStart.set(Calendar.MINUTE,0);

Upvotes: -2

Related Questions