Joda Time - convert a string to DateTime with a specific time zone and in a specific format

I want to convert a String Date to a DateTime object for a specific time zone and in a specific format. How can i do this?

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 time zone specified by the user.

Example: convert YYYY-MM-DD to MM / DD / YY for the Pacific time zone.

+4
source share
1 answer

Use DateTimeFormatterBuilder to create formatting that can parse / format multiple DateTimeFormat s and set the resulting DateTimeFormatter to use the 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 the given DateTime , you can simply use dttm1.toString("yyyy-MM-dd")) .

+7
source

Source: https://habr.com/ru/post/1434096/


All Articles