Jus*_*tin 0 java epoch simpledateformat
我的输入日期为"2020-10-31T00:00:00Z"。我想解析这个日期以获得长毫秒。 注意:转换后的毫秒数应为悉尼时间(即 GMT+11)。
供参考,
public static long RegoExpiryDateFormatter(String regoExpiryDate)
{
long epoch = 0;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("GMT+11"));
Date date;
try {
date = df.parse(regoExpiryDate);
epoch = date.getTime();
} catch (ParseException e) {
System.out.println("Exception is:" + e.getMessage());
e.printStackTrace();
}
System.out.println("Converted regoExpiryDate Timestamp*************** " + epoch);
return epoch;
}
Run Code Online (Sandbox Code Playgroud)
输出: 1604062800000使用Epoch Converter将日期设为30/10/2019,但在输入中我将第 31 天作为日期传递。任何人都可以澄清这一点吗?
通过这样做df.setTimeZone(TimeZone.getTimeZone("GMT+11"));,您是在要求日期格式化程序在 GMT+11 时区解释您的字符串。但是,不应在该时区解释您的字符串。Z在字符串中看到了吗?那代表 GMT 时区,所以你应该这样做:
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Run Code Online (Sandbox Code Playgroud)
事实上,您的字符串采用 ISO 8601 格式Instant(或“时间点”,如果您愿意)。因此,您可以使用 解析它Instant.parse,并使用以下方法获取毫秒数toEpochMilli:
System.out.println(Instant.parse("2020-10-31T00:00:00Z").toEpochMilli());
// prints 1604102400000
Run Code Online (Sandbox Code Playgroud)
警告:SimpleDateFormat如果 Java 8 API(即Instant诸如此类)可用,您就不应该再使用它了。即使不是,您也应该使用NodaTime或类似的东西。
| 归档时间: |
|
| 查看次数: |
11451 次 |
| 最近记录: |