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"))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With