我尝试通过以下方式转换此日期:
SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSSZ");
但我得到:
java.text.ParseException: Unparseable date: "2014-09-20 00:00:00 -0500" (at offset 20)
“-0500”是与 UTC 的偏移量,采用 RFC822 格式。您只想要
Z
,没有 SSS
。
SimpleDateFormat
文档在表中有这样的内容:
Z/ZZ/ZZZ
:-0800 ZZZZ
:GMT-08:00 ZZZZZ
:-08:00当然,我也会亲自指定一个语言环境:这是一种机器可读的格式,而不是面向人类的格式,所以我通常会指定
Locale.US
:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z",
Locale.US);
String text = "2014-08-20 00:00:00 -0500";
System.out.println(format.parse(text));
Jon Skeet的答案是正确的。
这里有一些示例代码,展示了如何将字符串转换为符合 ISO 8601。
String inputRaw = "2014-08-20 00:00:00 -0500";
String input = inputRaw.replaceFirst( " ", "T" ).replaceFirst( " ", "" ); // Replace first SPACE with a 'T', and delete second SPACE.
// input is "2014-08-20T00:00:00-0500".
您可以将该兼容字符串直接传递给 Joda-Time 中的 DateTime 构造函数。 Java 8 中的 java.time 包 中的等效项也是如此(受到 Joda-Time 的启发)。
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Specify it rather than have JVM's default applied.
DateTime dateTimeMontréal = new DateTime( input, timeZone );
DateTime dateTimeUtc = dateTimeMontréal.withZone( DateTimeZone.UTC );
转储到控制台。
System.out.println( "inputRaw: " + inputRaw );
System.out.println( "input: " + input );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
运行时...
inputRaw: 2014-08-20 00:00:00 -0500
input: 2014-08-20T00:00:00-0500
dateTimeMontréal: 2014-08-20T01:00:00.000-04:00
dateTimeUtc: 2014-08-20T05:00:00.000Z
java.time
2014 年 3 月,Java 8 引入了现代的
java.time
日期时间 API,取代了容易出错的旧版java.util
日期时间 API。任何新代码都应使用 java.time
API*。
另外,下面是Joda-Time主页上的通知:
请注意,从 Java SE 8 开始,用户被要求迁移到
(JSR-310) - JDK 的核心部分,它取代了这个 项目。java.time
您的文本字符串
2014-09-20 00:00:00 -0500
的时区偏移量为 -05:00
,即它代表 UTC 时间 2014-09-20 00:00:00
plus 5 小时,即 2014-09-20T05:00:00Z
(如下面的演示中所示),其中 Z
代表时区偏移 +00:00
。该文本应解析为现代 API 的 OffsetDateTime
。
演示:
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2014-09-20 00:00:00 -0500", dtf);
System.out.println(odt);
// What does it represent at UTC?
Instant instant = odt.toInstant();
System.out.println(instant);
}
}
输出:
2014-09-20T00:00-05:00
2014-09-20T05:00:00Z
注意: 如果由于某种原因,您需要
java.util.Date
的实例,请让 java.time
API 完成解析日期时间字符串的繁重工作,并将上述代码中的 instant
转换为 java.util.Date
实例使用 Date date = Date.from(instant)
。
从 Trail:日期时间了解有关现代日期时间 API 的更多信息。
* 如果您收到
java.util.Date
的实例,请使用 java.time.Instant
将其转换为
Date#toInstant
,并根据您的要求从中派生 java.time
的其他日期时间类。