java.time
java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,转用modern date-time API。
这里的关键是在给定字符串的毫秒数内得到Instant 的对象。拥有Instant 后,您可以将其转换为其他java.time types,例如ZonedDateTime 甚至是旧版java.util.Date。
关于正则表达式 \D+ 的注释:\D 指定 non-digit,而 + 指定其出现的 one or more。
演示:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String text = "/Date(1534291200000)/";
// Replace all non-digits i.e. \D+ with a blank string
Instant instant = Instant.ofEpochMilli(Long.parseLong(text.replaceAll("\\D+", "")));
System.out.println(instant);
// Now you can convert Instant to other java.time types e.g. ZonedDateTime
// ZoneId.systemDefault() returns the time-zone of the JVM. Replace it with the
// desired time-zone e.g. ZoneId.of("Europe/London")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
// Print the default format i.e. the value of zdt#toString
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd HH:mm:ss uuuu", Locale.ENGLISH);
String strDateTimeFormatted = zdt.format(dtf);
System.out.println(strDateTimeFormatted);
}
}
输出:
2018-08-15T00:00:00Z
2018-08-15T01:00+01:00[Europe/London]
Wed August 15 01:00:00 2018
如何从Instant 获取java.util.Date?
您应该避免使用java.util.Date,但无论出于何种目的,如果您想获得java.util.Date,您所要做的就是使用Date#from,如下所示:
Date date = Date.from(instant);
PT12H18M02S 呢?
您可以将其解析为java.time.Duration,它以ISO-8601 standards 为模型,并作为JSR-310 implementation 的一部分与Java-8 一起引入。
如果您浏览过上述链接,您可能已经了解到PT12H18M02S 指定的持续时间为 12 小时 18 分 2 秒,您将其添加到日期时间对象(例如上面获得的zdt)以获得一个新的日期时间。
Duration duration = Duration.parse("PT12H18M02S");
ZonedDateTime zdtUpdated = zdt.plus(duration);
System.out.println(zdtUpdated);
输出:
2018-08-15T13:18:02+01:00[Europe/London]
从 Trail: Date Time 了解现代日期时间 API。
如何在 JDBC 中使用java.time 类型?
PostgreSQL™ JDBC 驱动程序使用 JDBC 4.2 实现对 Java 8 日期和时间 API (JSR-310) 的原生支持。
请注意,不支持 ZonedDateTime、Instant 和 OffsetTime / TIME [ WITHOUT TIMEZONE ]。另外,请注意所有OffsetDateTime 实例都必须在UTC 中(偏移量为0)。这是因为后端将它们存储为UTC。
OffsetDateTime odt = zdt.withZoneSameInstant(ZoneOffset.UTC).toOffsetDateTime();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();