Java 中设置当前时间有两种方法:使用 System.currentTimeMillis() 返回自 1970 年以来的毫秒数。使用 Instant.now() 返回自 1970 年以来的纳秒数,可通过 Instant.toEpochMilli() 转换为毫秒数。
在 Java 中,我们可以使用两种主要方法来
设置当前时间:
System.currentTimeMillis() 方法返回当前时间自 1970 年 1 月 1 日 00:00:00 GMT 以来经过的毫秒数。
long currentTime = System.currentTimeMillis();
Instant.now() 方法返回当前时间作为 Instant 对象,Instant 表示一个时间戳,代表自 1970 年 1 月 1 日 00:00:00 GMT 以来经过的纳秒数。
Instant currentTime = Instant.now();
注意: Instant 类表示的是时间戳,而 System.currentTimeMillis() 方法返回的是毫秒数。因此,在实际使用中,需要根据需要进行转换。
long currentTimeMillis = currentTime.toEpochMilli();
Instant currentTime = Instant.ofEpochMilli(currentTimeMillis);