z
是有效的模式
SimpleDateFormat
javadoc
,它是时区指示符)
任何
场所
唯一的区别是,对于某些值,结果可能取决于区域设置(例如:如果使用
zzzz
America/Los_Angeles
可以格式化为
太平洋夏令时
Horrio de luz natural do Pacfico公司
z
和
getDateTimeInstance
将使用预定义的内置硬编码模式。由于短模式通常不包括时区,因此您必须添加
z
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH);
SimpleDateFormat sf = (SimpleDateFormat) f;
String pattern = sf.toPattern();
// add z to the format, use the same locale
SimpleDateFormat sdf = new SimpleDateFormat(pattern + " z", Locale.ENGLISH);
Java新日期/时间API
旧阶级(
Date
Calendar
和
日期格式
lots of problems
和
design issues
当你使用
Java 8
,考虑使用
new java.time API
less bugged and less error-prone than the old APIs
.
不幸的是,预定义的内置模式仍然是硬编码的,您必须手动添加时区,但至少您可以摆脱上面链接中解释的所有问题:
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.time.ZonedDateTime;
// get built-in localized format for a specified locale
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT,
FormatStyle.SHORT, IsoChronology.INSTANCE, Locale.ENGLISH);
// create a formatter, add the timezone manually, use same locale
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern + " z", Locale.ENGLISH);
// format a date
System.out.println(fmt.format(ZonedDateTime.now()));
当你打印时区时,我使用
ZonedDateTime
,表示特定时区中的日期和时间。检查
tutorial
有关新日期类型的更多详细信息。
DateTimeFormatter
. 检查
javadoc
详细信息。
如果您仍然需要与
java.util.Date
// convert to Instant (UTC)
ZonedDateTime z = new Date().toInstant()
// convert to some timezone
.atZone(ZoneId.of("Europe/London"));
API使用
IANA timezones names
(始终采用格式
Continent/City
喜欢
America/Sao_Paulo
Europe/Berlin
避免使用三字母缩写(如
CST
或
PST
ambiguous and not standard
.