tl;博士
LocalDateTime.parse( // Parse as a date-time lacking time zone or offset-from-UTC.
"12/01/2014 05:30:15 PM" , // Define a formatting pattern to match input. Case-sensitive formatting code. Use `h` lowercase for 12-hour clock, 0-12. Use uppercase `H` for 24-hour clock, 0-23.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
).format( // Generate a String in specific format. Generally better to let java.time localize automatically.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
)
java.time
现代方法使用 java.time 类取代了麻烦的旧日期时间类。
获取 UTC 中的当前时刻。 Instant 类代表UTC 时间线上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。
Instant instant = Instant.now() ;
要通过某个地区(时区)的人们使用的挂钟时间的镜头看到同一时刻,请申请ZoneId 以获得ZonedDateTime。
以continent/region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 3-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
要在其中任何一个上生成标准 ISO 8601 格式的字符串,请调用 toString。 java.time 类在解析/生成字符串时默认使用标准格式。所以不需要指定格式模式。
如果您想要其他格式,请使用 DateTimeFormatter 或 DateTimeFormatterBuilder 类。您可以指定格式模式,但更容易让 java.time 自动本地化。
要本地化,请指定:
-
FormatStyle 确定字符串的长度或缩写。
-
Locale 确定 (a) 用于翻译日期名称、月份名称等的人类语言,以及 (b) 决定缩写、大写、标点符号、分隔符等问题的文化规范。
例子:
Locale l = Locale.FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
mercredi 14 février 2018 à 00:59:07 heure normale d'Europe centrale
或者,Locale.US & FormatStyle.SHORT。
2/14/18,凌晨 1:01
您输入的自定义格式是:
String input = "12/01/2014 05:30:15 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US ) ;
该输入字符串缺少任何时区指示符或与 UTC 的偏移量。所以它不是片刻,不是时间线上的一个特定点。它代表了一个关于在大约 26-27 小时范围内的潜在时刻的模糊概念。因此,我们将此输入解析为缺少任何区域/偏移量概念的LocalDateTime。
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2014-12-01T17:30:15
生成该格式的字符串。
String output = ldt.format( f ) ;
2014 年 12 月 1 日下午 5:30:15
正如其他人所解释的,格式代码区分大小写。如果您想要 24 小时制,请使用大写的 H。对于 12 小时时间,请使用小写 h。
请注意,java.time 中的格式代码与旧版 SimpleDateFormat 的格式代码接近,但并不完全相同。研究文档并在 Stack Overflow 上搜索许多示例。
在将日期时间值交换为文本时,请坚持使用标准的 ISO 8601 格式。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
使用符合JDBC 4.2 或更高版本的JDBC driver,您可以直接与您的数据库交换java.time 对象。不需要字符串也不需要 java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。