java - 解析格式化的日期在 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
.
解决方案
您正在使用不同的格式模式进行格式化和以后的解析。
尝试
currentDateHongkong = hongkongDateFromat.parse(stringFormatDate, new ParsePosition(0));
代替
currentDateHongkong = new SimpleDateFormat(dateFormat).parse(stringFormatDate, new ParsePosition(0));
推荐阅读
- bind - 如何在 ionic 4 中绑定离子按钮的背景颜色
- sql - ASP.NET 登录和注册在 Visual Studio 中有效,但在发布到 IIS 时无效
- python - Tensorflow:压缩两个不同形状的张量的第一维
- sql - HQL 查询中不需要的隐式内部联接
- java - Transactional Producer vs Just Idempotent Producer Java (Exception OutOfOrderSequenceException)
- anaconda - Anaconda 返回错误“系统找不到指定的文件”
- r - 如果 ==0,则仅替换指定列中的值
- html - 如何将填充放在图像边框之外?
- react-native - 更改状态以呈现不同的远程图像uri时如何停止图像闪烁?
- reactjs - Vega 图表仅在使用 React 时在悬停时呈现