tl;博士
LocalDateTime.parse( // Parse string as value without time zone and without offset-from-UTC.
"2017-01-23 12:34 PM" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" )
) // Returns a `LocalDateTime` object.
.atZone( ZoneId.of( "America/Montreal" ) ) // Assign time zone, to determine a moment. Returns a `ZonedDateTime` object.
.toInstant() // Adjusts from zone to UTC.
.toString() // Generate string: 2017-01-23T17:34:00Z
.replace( "T" , " " ) // Substitute SPACE for 'T' in middle.
.replace( "Z" , " Z" ) // Insert SPACE before 'Z'.
避免使用旧的日期时间类
其他答案使用麻烦的旧日期时间类(Date、Calendar 等),现在是遗留的,被 java.time 类取代。
LocalDateTime
我有一个模式为 yyyy-MM-dd hh:mm a 的字符串
这样的输入字符串缺少任何与 UTC 或时区偏移的指示。所以我们解析为LocalDateTime。
定义格式模式以将您的输入与DateTimeFormatter 对象匹配。
String input = "2017-01-23 12:34 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2017-01-23T12:34
请注意,LocalDateTime不是特定时刻,只是关于一系列可能时刻的模糊概念。例如,法国巴黎午夜过后的几分钟,在加拿大蒙特利尔仍然是“昨天”。因此,如果没有 Europe/Paris 或 America/Montreal 等时区的上下文,仅仅说“午夜后几分钟”是没有意义的。
ZoneId
我可以单独获取上面字符串代表日期的时区对象。
时区由ZoneId 类表示。
以continent/region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 3-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime
应用ZoneId 得到ZonedDateTime,这确实是时间轴上的一个点,一个特定的历史时刻。
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2017-01-23T12:34-05:00[美国/蒙特利尔]
Instant
我想将其转换为以下格式。 yyyy-MM-dd HH:mm:ss Z
首先,要知道Z 文字字符是Zulu 的缩写,意思是UTC。换句话说,零小时的offset-from-UTC,+00:00。
Instant 类表示UTC 中时间轴上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。
您可以从ZonedDateTime 中提取Instant 对象。
Instant instant = zdt.toInstant(); // Extracting the same moment but in UTC.
要生成标准ISO 8601 格式的字符串,例如2017-01-22T18:21:13.354Z,请调用toString。标准格式没有空格,使用T 将年-月-日与时-分-秒分开,并规范地附加Z 以获得零偏移量。
String output = instant.toString();
instant.toString(): 2017-01-23T17:34:00Z
我强烈建议尽可能使用标准格式。如果您坚持按照您声明的所需格式使用空格,请在DateTimeFormatter 对象中定义您自己的格式模式,或者只是对Instant::toString 的输出进行字符串操作。
String output = instant.toString()
.replace( "T" , " " ) // Substitute SPACE for T.
.replace( "Z" , " Z" ); // Insert SPACE before Z.
输出:2017-01-23 17:34:00 Z
试试这个code live at IdeOne.com。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。