Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Time - Convert a String into a DateTime with a particular timezone and in a particular format

Tags:

java

jodatime

I want to convert a String Date into a DateTime object for a particular timezone and in a particular format. How can I do it ?

String Date can be in any format used in the world. Example MM-DD-YYYY, YYYY-MM-DD, MM/DD/YY , MM/DD/YYYY etc. TimeZone can be any legal timezone specified by the user.

Example - convert YYYY-MM-DD into MM/DD/YY for the Pacific Timezone.

like image 869
david blaine Avatar asked Feb 20 '23 04:02

david blaine


1 Answers

Use DateTimeFormatterBuilder to build a formatter that is able to parse/format multiple DateTimeFormats, and set the resulting DateTimeFormatter to use a specified DateTimeZone:

DateTimeParser[] parsers = { 
  DateTimeFormat.forPattern("MM-dd-yyyy").getParser(),
  DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
  DateTimeFormat.forPattern("MM/dd/yyyy").getParser(),
  DateTimeFormat.forPattern("yyyy/MM/dd").getParser()
};

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .append(null, parsers)
  .toFormatter()
  .withZone(DateTimeZone.UTC);

DateTime dttm1 = formatter.parseDateTime("01-31-2012");
DateTime dttm2 = formatter.parseDateTime("01/31/2012");
DateTime dttm3 = formatter.parseDateTime("2012-01-31");

To format a given DateTime you can just use dttm1.toString("yyyy-MM-dd")).

like image 153
João Silva Avatar answered Apr 25 '23 14:04

João Silva