3

我正在格式化 UTC 日期,我希望它以当地时间显示。但是,使用withZone(ZoneId.systemDefault());什么也没做。这是一些代码, and 的值dd2相同的,但我预计 d2 会提前 6 小时,因为我在 MST 中。

    public static final String DATE_TIME_PATTERN = "uuuuMMddHHmmss";

    String date = "20160908222020";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN).withZone(ZoneId.systemDefault());
    LocalDateTime d = LocalDateTime.parse(date, formatter);
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
    LocalDateTime d2 = LocalDateTime.parse(date, formatter2);
4

1 回答 1

2

使用 SimpleDateFormat,更容易理解正在发生的事情(这种方法对我有用)。

public static final String SOURCE_DATE_FORMAT = "yyyyMMddHHmmss";
String date = "20160908222020";

SimpleDateFormat sourceDateFormat = new SimpleDateFormat(SOURCE_DATE_FORMAT);
sourceDateFormat.setTimeZone("UTC"); // set this to whatever the source time zone is

String adjustedDate = "";
try {
    Date parsedDate = sourceDateFormat.parse(date);
    adjustedDate = DateFormat.getDateTimeInstance().format(parsedDate); // getDateTimeInstance() returns the local date/time format (in terms of language/locale and time zone) of the device and format() formats the parsed date to fit that instance
} catch (ParseException e) {
    e.printStackTrace();
}
于 2016-09-12T16:31:19.940 回答