user798759
user798759

Reputation: 42

Calendar returning the wrong time

The time displayed is way ahead of what I expected. I'm parsing a date string and turning it into milliseconds.

year = Integer.parseInt(m1.group(1));
mo = Integer.parseInt(m1.group(2));
day = Integer.parseInt(m1.group(3));
hr = Integer.parseInt(m1.group(4));
min = Integer.parseInt(m1.group(5));
sec = Integer.parseInt(m1.group(6));

and here I set the Calendar

Calendar cal = Calendar.getInstance();
cal.set(year, mo, day, hr, min, sec);
time = cal.getTimeInMillis();

Upvotes: 0

Views: 328

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 340070

java.time

Update: The terribly-flawed Calendar class is now legacy, supplanted by the modern java.time classes. Among its many flaws is crazy zero-based counting of months.

In contrast, java.time uses sane counting. Months are 1-12 for January-December.

LocalDate date = LocalDate.of ( year , month , day ) ;
LocalTime time = LocalTime.of ( hour , minute , second ) ;
ZoneId z = ZoneId.of ( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.of ( date , time , zone ) ;

Upvotes: 1

Kevin C
Kevin C

Reputation: 5395

If you check out the calendar documentation here, then visit here, you'll see that January is month 0. You'll want to change your code to mo = Integer.parseInt(m1.group(2))-1;

Upvotes: 4

Thilo
Thilo

Reputation: 262814

You should probably use DateFormatter to parse the date string (rather than rolling your own).

Other than that, make sure that you have the proper time zone and understand that month number one is February (not January).

Upvotes: 0

Related Questions