Android DateTimeFormatter withZone 不工作
Android DateTimeFormatter withZone not working
我正在格式化一个 UTC 日期,我希望它以当地时间显示。但是,使用 withZone(ZoneId.systemDefault());
什么都不做。
这是一些代码,d
和 d2
的值相同,但我希望 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);
使用 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();
}
我正在格式化一个 UTC 日期,我希望它以当地时间显示。但是,使用 withZone(ZoneId.systemDefault());
什么都不做。
这是一些代码,d
和 d2
的值相同,但我希望 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);
使用 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();
}