将“ 2020-10-31T00:00:00Z”转换为长日期[重复项]

问题描述 投票:0回答:1
我的输入日期为

“ 2020-10-31T00:00:00Z”。我想解析此日期以获取长毫秒。注意:转换后的毫秒数应为悉尼时间(即GMT + 11)。

FYI,

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; }

Output:

1604062800000通过使用Epoch Converter将Date表示为30/10/2019,但在输入中,我将31st作为Date传递。任何人都可以澄清一下吗?
java simpledateformat epoch
1个回答
4
投票
通过df.setTimeZone(TimeZone.getTimeZone("GMT+11"));,您正在要求日期格式化程序在GMT + 11时区中解释您的字符串。但是,不应在该时区中解释您的字符串。看到字符串中的Z吗?这代表格林尼治标准时间(GMT)时区,因此您应该这样做:

df.setTimeZone(TimeZone.getTimeZone("GMT"));

实际上,您的字符串是Instant的ISO 8601格式(如果愿意,也可以是“时间点”)。因此,您可以使用Instant.parse进行解析,并使用toEpochMilli来获取毫秒数:

System.out.println(Instant.parse("2020-10-31T00:00:00Z").toEpochMilli()); // prints 1604102400000

警告:如果Java 8 API(即SimpleDateFormat等)可用,您就不再应该真正使用Instant。即使不是,也应使用NodaTime或类似的东西。

© www.soinside.com 2019 - 2024. All rights reserved.