Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Time - Converting Calendar object to LocalDate

I have a method getCalendarFromClass that returns me an object of Calendar.

And I am converting it into LocalDate of Joda Time API using fromCalendarFields method.

LocalDate.fromCalendarFields(a.getCalendarFromClass());

But how can specify the TimeZone when performing this conversion as I didn't found it in javadoc.

The javadoc for fromCalendarFields method mentions :

Each field is queried from the Calendar and assigned to the LocalDate. This is useful if you have been using the Calendar as a local date, ignoring the zone.

like image 426
Abubakkar Avatar asked Nov 27 '12 13:11

Abubakkar


3 Answers

1) Get the timezone:

TimeZone tz = calendar.getTimeZone();

2) Create a Joda DateTime from Calendar:

DateTimeZone jodaTz = DateTimeZone.forID(tz.getID());
DateTime dateTime = new DateTime(calendar.getTimeInMillis(), jodaTz);

3) Get a LocalDate

LocalDate localDate = dateTime.toLocalDate();
like image 131
Tom Carchrae Avatar answered Sep 29 '22 12:09

Tom Carchrae


The Calendar has a time zone, and that will be used (by the Calendar) when Joda Time requests the different field values. Joda Time just uses calendar.get(Calendar.YEAR) etc.

The returned LocalDate doesn't have a time zone, conceptually.

like image 45
Jon Skeet Avatar answered Sep 29 '22 13:09

Jon Skeet


LocalDate doesn't look like the class you want. From the doc:

LocalDate is an immutable datetime class representing a date without a time zone.

(my emphasis)

like image 45
Brian Agnew Avatar answered Sep 29 '22 12:09

Brian Agnew