前言
java.time.Instant 类是 Java 8 新增的日期时间 API 的一部分,用于表示时间线上的一个瞬时点。它是不可变的、线程安全的,并且设计用来代替 java.util.Date。
Instant 可以被用来记录事件发生的时间戳,以及进行时间戳的计算和转换操作。
Instant 类主要存储两部分数据:
- 自1970年1月1日0时0分0秒(UTC)开始的秒数。
- 纳秒部分(秒内的纳秒数),以提供更精确的时间。
java.time.Instant 类的一些常用方法:
demo
now() - 获取当前的时间戳。
ofEpochMilli(long epochMilli) - 使用从1970-01-01T00:00:00Z的UTC开始的毫秒数创建一个 Instant 实例。
ofEpochSecond(long epochSecond) - 使用从1970-01-01T00:00:00Z的UTC开始的秒数创建一个 Instant 实例,可以另外加上纳秒的调整值。
plusSeconds(long secondsToAdd) - 添加指定的秒数到这个 Instant。
plusMillis(long millisToAdd) - 添加指定的毫秒数到这个 Instant。
plusNanos(long nanosToAdd) - 添加指定的纳秒数到这个 Instant。
minusSeconds(long secondsToSubtract) - 从这个 Instant 减去指定的秒数。
minusMillis(long millisToSubtract) - 从这个 Instant 减去指定的毫秒数。
minusNanos(long nanosToSubtract) - 从这个 Instant 减去指定的纳秒数。
getEpochSecond() - 获取这个 Instant 的秒数部分。
toEpochMilli() - 将这个 Instant 转换为毫秒数。
atZone(ZoneId zone) - 将这个 Instant 转换为在指定时区的 ZonedDateTime。
isAfter(Instant otherInstant) - 检查这个 Instant 是否在参数表示的时间点之后。
isBefore(Instant otherInstant) - 检查这个 Instant 是否在参数表示的时间点之前。
compareTo(Instant otherInstant) - 比较两个 Instant 的时间顺序。
equals(Object otherInstant) - 检查这个 Instant 是否与另一个对象相等。
import java.time.Instant;
public class InstantExample {
public static void main(String[] args) {
Instant now = Instant.now(); // 获取当前瞬时点
System.out.println("Current Timestamp: " + now);
// 增加5小时
Instant fiveHoursLater = now.plusSeconds(5 * 3600);
System.out.println("Five hours later: " + fiveHoursLater);
// 检查先后顺序
boolean isAfter = fiveHoursLater.isAfter(now);
System.out.println("Is five hours later after now? " + isAfter);
// 转换为毫秒
long milliseconds = now.toEpochMilli();
System.out.println("Milliseconds since epoch: " + milliseconds);
}
// 解析文本字符串为Instant
Instant specificTime = Instant.parse("2023-03-23T10:15:30.00Z");
System.out.println("Specific time: " + specificTime);
// 截断到小时(忽略更小的时间单位)
Instant truncatedToHours = instant.truncatedTo(ChronoUnit.HOURS);
System.out.println("Truncated to hours: " + truncatedToHours);
// 计算两个Instant之间的分钟数
long minutesUntil = instant.until(specificTime, ChronoUnit.MINUTES);
System.out.println("Minutes until specific time: " + minutesUntil);
// 获取纳秒部分
int nanoPart = instant.getNano();
System.out.println("Nano part of the current instant: " + nanoPart);
ZonedDateTime zdt = now.atZone(ZoneId.systemDefault());
// 获取本月的第一天
ZonedDateTime firstDayOfMonth = zdt.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("First day of the month: " + firstDayOfMonth);
// 获取本月的最后一天
ZonedDateTime lastDayOfMonth = zdt.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("Last day of the month: " + lastDayOfMonth);
// 获取下一个星期一
ZonedDateTime nextMonday = zdt.with(TemporalAdjusters.next(ChronoUnit.MONDAYS));
System.out.println("Next Monday: " + nextMonday);
}
}