简体   繁体   中英

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

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.

Use DateTimeFormatterBuilder to build a formatter that is able to parse/format multiple DateTimeFormat s, 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")) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM