将“2020-10-31T00:00:00Z”字符串日期转换为长

Convert "2020-10-31T00:00:00Z" String Date to long

我将输入日期设置为 "2020-10-31T00:00:00Z"。我想解析这个 Date 以获得 Long 毫秒。 注意:转换后的毫秒数应为悉尼时间(即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;
    }

输出: 1604062800000 通过使用 30/10/2019 =11=],但在输入中我将 31 日作为日期传递。 谁能澄清一下?

通过执行 df.setTimeZone(TimeZone.getTimeZone("GMT+11"));,您要求日期格式化程序在 GMT+11 时区解释您的字符串。但是,不应在该时区解释您的字符串。看到字符串中的 Z 了吗?那代表 GMT 时区,所以你应该这样做:

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

事实上,您的字符串采用 Instant(或 "point in time",如果您愿意)的 ISO 8601 格式。因此,您可以使用 Instant.parse 解析它,并使用 toEpochMilli:

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

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