在java中用时区解析时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22783439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing timestamp with timezone in java?
提问by Karthik
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 ?
有谁知道如何解决这一问题 ?
回答by assylias
You need to use X
instead of Z
:
您需要使用X
代替Z
:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSX");
See the javadocfor more info.
有关更多信息,请参阅javadoc。
Note: only available in Java 7+.
注意:仅在 Java 7+ 中可用。
回答by Ben S
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 X
s to get the specific colon-separated offset that you're using.
如果您要在 Java 8 中使用新的 JSR 310 日期/时间 API,您可以使用该XXX
格式来解析时区。您需要三个X
s 才能获得您正在使用的特定冒号分隔偏移量。
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