乔达时间
仅供参考,这是相同类型的代码,但在 Joda-Time 2.4 中完成。 Java 8 中的新 java.time package(受 Joda-Time 启发)可以以类似的方式使用。
java.util.Date 和 .Calendar 类是出了名的麻烦。避开他们。使用上面提到的两个库中的任何一个。
示例代码
您的输入字符串接近标准ISO 8601 格式,但不完全是,缺少中间的T 和与UTC 的偏移量。 Joda-Time 有一个用于在 ISO 8601 中解析/生成的内置格式化程序。因此,与其定义我们自己的格式化程序,让我们稍微调整一下输入字符串,插入 T。
String inputRaw = "2014-07-04 04:05:10"; // UTC
String input = inputRaw.replace( " ", "T" ); // Convert to standard ISO 8601 format.
然后我们将告诉 DateTime 构造函数将字符串解析为 UTC(零偏移)。与 java.util.Date 不同,DateTime 知道自己分配的时区。
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
轻松适应多伦多时间、娱乐或调试/健全性检查。
DateTime dateTimeToronto = dateTimeUtc.withZone( DateTimeZone.forID( "America/Toronto" ) );
与 java.util.Date 一样,Joda-Time 在内部以milliseconds 的数量跟踪时间,自 UTC 的 Unix 纪元(1970 年开始)以来。这意味着使用 64 位 long 而不是通常的 32 位 int。 (顺便说一句,java.time 跟踪 nanoseconds。)所以如果我们需要 seconds-since-unix-epoch,除以一千。
long millisecondsSinceEpoch = dateTimeUtc.getMillis(); // Use a "long", not "int".
long secondsSinceEpoch = ( millisecondsSinceEpoch / 1000L );
转储到控制台。
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeToronto: " + dateTimeToronto );
System.out.println( "millisecondsSinceEpoch: " + millisecondsSinceEpoch );
System.out.println( "secondsSinceEpoch: " + secondsSinceEpoch );
运行时。
input: 2014-07-04T04:05:10
dateTimeUtc: 2014-07-04T04:05:10.000Z
dateTimeToronto: 2014-07-04T00:05:10.000-04:00
millisecondsSinceEpoch: 1404446710000
secondsSinceEpoch: 1404446710