Android DateTimeFormatter withZone无法正常工作

时间:2016-09-12 14:43:53

标签: java android datetime datetime-format localdate

我格式化UTC日期,我希望它以当地时间显示。但是,使用withZone(ZoneId.systemDefault());不会做任何事情。 这里有一些代码,dd2的值相同,但我希望d2提前6小时,因为我在MST中。< / p>

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

1 个答案:

答案 0 :(得分: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();
}