java 得到当前时间戳
在Java中,你可以使用java.time包(自Java 8开始引入)的类来获取当前的时间戳。
以下是几种获取当前时间戳的方法:
- 使用Instant类: 这将为你提供一个基于UTC的时间戳。
Instant timestamp = Instant.now();
- 使用System类的currentTimeMillis()方法: 这将返回1970年1月1日(UTC)至今的毫秒数,这也常被用作时间戳。
long timestamp = System.currentTimeMillis();
- 使用LocalDateTime和ZoneId: 如果你需要一个具体时区的时间戳,可以使用LocalDateTime,然后转换为指定时区。
LocalDateTime now = LocalDateTime.now();
long timestamp = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
请注意,这些方法都会基于当前的系统时间来生成时间戳。