17370845950

java当前时间怎么设置
Java 中设置当前时间有两种方法:使用 System.currentTimeMillis() 返回自 1970 年以来的毫秒数。使用 Instant.now() 返回自 1970 年以来的纳秒数,可通过 Instant.toEpochMilli() 转换为毫秒数。

Java 中设置当前时间的两种方法

在 Java 中,我们可以使用两种主要方法来设置当前时间:

方法一:使用 System.currentTimeMillis()

System.currentTimeMillis() 方法返回当前时间自 1970 年 1 月 1 日 00:00:00 GMT 以来经过的毫秒数。

long currentTime = System.currentTimeMillis();

方法二:使用 Instant.now()

Instant.now() 方法返回当前时间作为 Instant 对象,Instant 表示一个时间戳,代表自 1970 年 1 月 1 日 00:00:00 GMT 以来经过的纳秒数。

Instant currentTime = Instant.now();

注意: Instant 类表示的是时间戳,而 System.currentTimeMillis() 方法返回的是毫秒数。因此,在实际使用中,需要根据需要进行转换。

转换 Instant 到毫秒数:

long currentTimeMillis = currentTime.toEpochMilli();

转换毫秒数到 Instant:

Instant currentTime = Instant.ofEpochMilli(currentTimeMillis);