首页 > 解决方案 > 解析格式化的日期在 Java 11 中给出 null 但在 Java 8 中给出正确的输出

问题描述

这是在 Java 8 中正常工作并打印所需输出的代码。

import java.util.*;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;

public class Java11 {

    public static void main(String args[]) throws Exception {

        // Hong kong timezone ID.
        String hongkongTimezone = "Asia/Hong_Kong";
        String dateFormat = "MMM dd, yyyy HH:mm:SS";

        //Current date of local time zone.
        Date date = new Date();

        // Current date of HongKong.
        Date currentDateHongkong = null;

        DateFormat hongkongDateFromat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US);

        // Set hongkong time zone ID.
        hongkongDateFromat.setTimeZone(TimeZone.getTimeZone(hongkongTimezone));
        String stringFormatDate = hongkongDateFromat.format(date);

        currentDateHongkong = new SimpleDateFormat(dateFormat).parse(stringFormatDate, new ParsePosition(0));

        System.out.println(currentDateHongkong);
    }
}

在 Java 8 上执行时输出如下

Mon Oct 22 06:28:00 IST 2018

但是当我在 Java 11 上执行相同的代码时,我得到null.

标签: javadatetime-formatjava-11

解决方案


您正在使用不同的格式模式进行格式化和以后的解析。

尝试

currentDateHongkong = hongkongDateFromat.parse(stringFormatDate, new ParsePosition(0));

代替

currentDateHongkong = new SimpleDateFormat(dateFormat).parse(stringFormatDate, new ParsePosition(0));

推荐阅读