Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time DateTime formatting based on locale

I receive a string date from another system and I know the locale of that date (also available from the other system). I want to convert this String into a Joda-Time DateTime object without explicitly specifying the target pattern.

So for example, I want to convert this String "09/29/2014" into a date object using the locale only and not by hard coding the date format to "mm/dd/yyyy". I cant hard code the format as this will vary depending on the local of the date I receive.

like image 351
Brian Avatar asked Sep 29 '14 14:09

Brian


People also ask

How do I change the date format in Joda-time?

How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.

Is Joda DateTime deprecated?

So the short answer to your question is: YES (deprecated).

Does Joda DateTime have timezone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.

What is Joda-time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.


1 Answers

String localizedCalendarDate = DateTimeFormat.shortDate().print(new LocalDate(2014, 9, 29));
// uses in Germany: dd.MM.yyyy
// but uses in US: MM/dd/yyyy

LocalDate date =
  DateTimeFormat.mediumDate().withLocale(Locale.US).parseLocalDate("09/29/2014");
DateTime dt = date.toDateTimeAtStartOfDay(DateTimeZone.forID("America/Los_Angeles"));

As you can see, you will also need to know the clock time (= start of day in example) and time zone (US-California in example) in order to convert a parsed date to a global timestamp like DateTime.

like image 138
Meno Hochschild Avatar answered Oct 13 '22 00:10

Meno Hochschild