Abubakkar
Abubakkar

Reputation: 15644

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.

Upvotes: 7

Views: 22983

Answers (3)

Tom Carchrae
Tom Carchrae

Reputation: 6486

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();

Upvotes: 11

Brian Agnew
Brian Agnew

Reputation: 272277

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)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 7

Related Questions