Skip to content

Instant 时间戳

Instant 表示时间线上的一个瞬时点,类似于 Unix 时间戳,但精度更高(纳秒)。

什么时候用 Instant

┌─────────────────────────────────────────────────────────────────┐
│                    日期时间类型选择指南                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Instant                    - 机器时间(时间戳)                   │
│  LocalDateTime              - 人类时间(不带时区)                  │
│  ZonedDateTime             - 人类时间(带时区)                    │
│                                                                  │
│  Instant 用于:                                                  │
│  ✅ 日志时间戳(便于排序和计算)                                   │
│  ✅ 性能测量                                                    │
│  ✅ 数据库 timestamp                                             │
│  ✅ 跨时区数据传输                                              │
│                                                                  │
│  LocalDateTime 用于:                                           │
│  ✅ 业务日期时间(显示给用户)                                    │
│  ✅ 定时任务                                                    │
│  ✅ 日程安排                                                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

创建 Instant

java
import java.time.*;

// 当前时间(UTC)
Instant now = Instant.now();
System.out.println(now);  // 2024-01-15T06:30:45.123456789Z

// 从 Unix 时间戳(秒)
Instant fromEpochSecond = Instant.ofEpochSecond(0);  // 1970-01-01T00:00:00Z
Instant fromEpochMilli = Instant.ofEpochMilli(System.currentTimeMillis());

// 从字符串
Instant parsed = Instant.parse("2024-01-15T10:30:00Z");

时间戳转换

java
Instant now = Instant.now();

// 获取秒/毫秒
long epochSecond = now.getEpochSecond();       // 秒
long epochMilli = now.toEpochMilli();          // 毫秒

// Duration:两个 Instant 之间的差
Instant start = Instant.now();
// ... 做点什么 ...
Instant end = Instant.now();

Duration elapsed = Duration.between(start, end);
System.out.println("耗时: " + elapsed.toMillis() + "ms");
System.out.println("耗时: " + elapsed.toMillis() + "ms");

与 Date 互转

java
import java.util.Date;

// Instant → Date
Instant instant = Instant.now();
Date date = Date.from(instant);

// Date → Instant
Date date = new Date();
Instant instant = date.toInstant();

// ⚠️ 注意:Instant 是 UTC 时间,Date 会转换成本地时区

与 LocalDateTime 互转

java
LocalDateTime ldt = LocalDateTime.of(2024, 1, 15, 14, 30);

// LocalDateTime → Instant(需要时区)
Instant instant1 = ldt.toInstant(ZoneOffset.UTC);
Instant instant2 = ldt.toInstant(ZoneId.of("Asia/Shanghai"));

// Instant → LocalDateTime
Instant instant = Instant.now();
LocalDateTime ldt1 = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDateTime ldt2 = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

常用计算

java
Instant now = Instant.now();

// 加减
Instant tomorrow = now.plus(1, java.time.temporal.ChronoUnit.DAYS);
Instant yesterday = now.minus(24, java.time.temporal.ChronoUnit.HOURS);

// 比较
Instant earlier = Instant.parse("2024-01-01T00:00:00Z");
Instant later = Instant.parse("2024-12-31T23:59:59Z");

earlier.isBefore(later);   // true
earlier.isAfter(later);    // false
earlier.isEqual(later);    // false

实战场景

场景一:计算代码执行时间

java
public long measure(Runnable action) {
    Instant start = Instant.now();
    action.run();
    Instant end = Instant.now();
    return Duration.between(start, end).toMillis();
}

// 使用
long ms = measure(() -> {
    // 要测量的代码
    Arrays.sort(new int[10000]);
});
System.out.println("耗时: " + ms + "ms");

场景二:日志时间戳

java
public void log(String message) {
    Instant timestamp = Instant.now();
    String logLine = String.format("[%s] %s", timestamp, message);
    // 写入日志文件
}

场景三:订单超时检查

java
public boolean isOrderExpired(Instant orderTime, Duration timeout) {
    return Instant.now().isAfter(orderTime.plus(timeout));
}

// 使用
Instant orderTime = Instant.parse("2024-01-15T10:00:00Z");
boolean expired = isOrderExpired(orderTime, Duration.ofHours(24));

场景四:缓存过期

java
public class CacheEntry<T> {
    private final Instant createdAt;
    private final Duration ttl;
    private final T value;
    
    public boolean isExpired() {
        return Instant.now().isAfter(createdAt.plus(ttl));
    }
}

// 使用
CacheEntry<String> cache = new CacheEntry<>(
    Instant.now(),
    Duration.ofMinutes(30),
    "some data"
);

if (cache.isExpired()) {
    // 重新加载
}

小结

方法说明
Instant.now()获取当前 UTC 时间
ofEpochSecond(millis)从 Unix 时间戳创建
toEpochMilli()转毫秒
plus/minus加减时间
isBefore/isAfter比较

记住:Instant 是机器时间,用于程序内部计算;LocalDateTime 是人类时间,用于显示给用户。

基于 VitePress 构建