I have a below code
final DateTimeFormatter COMBINED_FORMAT = ISODateTimeFormat.dateTimeParser().withZone(
DateTimeZone.UTC);
System.out.println(COMBINED_FORMAT.parseDateTime("2012-04-01T00:00:00.000").toDate());
Result is Sun Apr 01 05:30:00 IST 2012 I expect this to return Sun Apr 01 00:00:00 IST 2012
How can I get this?
First, you should not use java.util.Date.toString() (implicitly used in your example) to evaluate the result. Reason is its confusing behaviour to always output in your system timezone and not the real state of your result.
Second: If you set the zone to UTC then you instruct your parser to interprete the zone-less string "2012-04-01T00:00:00.000" as UTC and not as IST. Just look at the state of your result:
DateTimeFormatter COMBINED_FORMAT =
ISODateTimeFormat.dateTimeParser().withZone(DateTimeZone.UTC);
System.out.println(COMBINED_FORMAT.parseDateTime("2012-04-01T00:00:00.000"));
// 2012-04-01T00:00:00.000Z
However, if you want the result to be "Sun Apr 01 00:00:00 IST 2012" (output of date.toString()) or equivalent: "2012-04-01T00:00:00+05:30" then you have to instruct the parser to interprete the input as IST and not UTC.
Solution:
DateTimeFormatter COMBINED_FORMAT =
ISODateTimeFormat.dateTimeParser().withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(COMBINED_FORMAT.parseDateTime("2012-04-01T00:00:00.000"));
// 2012-04-01T00:00:00.000+05:30
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