Parsing timestamp with timezone in java?

那年仲夏 提交于 2019-12-31 01:51:07

问题


I'm trying to parse a string of format timestamp with timezone obtained from a DB. The String is as follows :

   SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSZ");

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); 
    Date d1 = mdyFormat.parse("2014-04-01 15:19:49.31146+05:30");

    String mdx = sdf.format(d1);

    System.out.println(mdx);

Problem is, I get an error saying :

Exception in thread "main" java.text.ParseException: Unparseable date: "2014-04-01 15:19:49.31146+05:30"
    at java.text.DateFormat.parse(DateFormat.java:357)
    at com.karthik.Timestampvalidate.main(Timestampvalidate.java:31)

Does anyone know how to fix this ?


回答1:


You need to use X instead of Z:

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSX");

See the javadoc for more info.

Note: only available in Java 7+.




回答2:


If you get to use the new JSR 310 date/time APIs in Java 8, you can use the XXX format to parse the timezone. You need three Xs to get the specific colon-separated offset that you're using.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSXXX");
TemporalAccessor dateTime = formatter.parse("2014-04-01 15:19:49.31146+05:30");
// returns: {OffsetSeconds=19800},ISO resolved to 2014-04-01T15:19:49.311460


来源:https://stackoverflow.com/questions/22783439/parsing-timestamp-with-timezone-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!