【发布时间】:2019-06-10 13:23:32
【问题描述】:
Java 的SimpleDateFormat 允许您在将字符串解析为Date 时指定要使用的TimeZone。
当字符串不包含时区时,这可以正常工作,但是当存在时区时,它似乎什么都不做。
文档似乎也没有真正解释 TimeZone 的使用方式。
示例代码:
public class DateFormatTest {
public static void main(final String[] args) throws ParseException {
testBoth("HH:mm", "13:40");
testBoth("HH:mm z", "13:40 UTC");
}
private static void testBoth(final String dateFormatString, final String dateString) throws ParseException {
// First, work with the "raw" date format
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
parse(dateFormat, dateString);
// Now, set the timezone to something else and try again
dateFormat = new SimpleDateFormat(dateFormatString);
dateFormat.setTimeZone(TimeZone.getTimeZone("PST"));
parse(dateFormat, dateString);
}
private static void parse(final DateFormat dateFormat, final String dateString) throws ParseException {
System.out.println(MessageFormat.format("Parsed \"{0}\" with timezone {1} to {2}", dateString,
dateFormat.getTimeZone().getDisplayName(), dateFormat.parse(dateString)));
}
}
示例输出:
Parsed "13:40" with timezone Greenwich Mean Time to 01/01/70 13:40
Parsed "13:40" with timezone Pacific Standard Time to 01/01/70 22:40
Parsed "13:40 UTC" with timezone Greenwich Mean Time to 01/01/70 14:40
Parsed "13:40 UTC" with timezone Pacific Standard Time to 01/01/70 14:40
请注意第一个示例中的 Date 如何更改 - 但对于第二个示例,它没有。
【问题讨论】:
-
提示:
PST不是实时时区。实时时区名称的格式为Continent/Region,例如America/Los_Angeles。 -
我建议你不要使用
SimpleDateFormat和DateFormat。这些课程是出了名的麻烦和过时。而是使用DateTimeFormatter、LocalTime和OffsetTime,均来自java.time, the modern Java date and time API。
标签: java simpledateformat date-format