-
java获取时间戳
Java获取时间戳的方法有哪些?动力节点小编来为大家总结一下。
1.使用 Instant 获取当前时间戳
Instant代表时间线中的一个独特点,主要用于记录应用程序中的事件时间戳。它是一个实际的时间点,使用UTC(通用时间尺度)表示。
Instant instant = Instant.now();
System.out.println(instant); //2022-02-15T08:06:21.410588500Z
2. java.sql.Timestamp (Java 7 或更早版本)
这个遗留类有 2 种方法来获取当前时间戳。
时间戳 timestamp1 = new Timestamp(System.currentTimeMillis());
日期日期 = 新日期();
时间戳 timestamp2 = new Timestamp(date.getTime());
System.out.println(timestamp1); //2022-02-15 13:55:56.18
System.out.println(timestamp2); //2022-02-15 13:55:56.18
3. Instant vs ZonedDateTime
在高层次上,Instant和ZonedDateTime类看起来很相似,但实际上并非如此。
ZonedDateTime是一个实际的时间点,但在特定的时区。
Instant是 UTC 中的一个时间点。
Instant.now()的值将在单词的所有部分中完全相同,而ZonedDateTime.now()的值将调整为与实例关联的时区值,
通常,考虑使用Instant类在数据库中存储时间戳值并在不同应用程序之间传递。并使用ZonedDateTime实例向特定时区的用户显示信息。