12

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Brian
  • 217
  • 1
  • 2
  • 11

1 Answers1

16
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.

Roy Shmuli
  • 4,979
  • 1
  • 24
  • 38
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • 2
    FYI, an alternate syntax is calling [`DateTimeFormat.forStyle()`](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html#forStyle(java.lang.String)) and passing a pair of characters. Pass one character for date portion and another for time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'. – Basil Bourque Sep 30 '14 at 04:43