Java8获取时间戳原来还有一个Instant

Instant你好 🚅

我说祝你开心的时候,是希望你真的开心,也知道开心很难,但不能因为开心很难,就不希望你开心

在 JDK8 中,可以使用 Instant 类来处理时间戳(timestamp),它表示从 1970 年 1 月 1 日 00:00:00 UTC(协调世界时)开始计算的秒数和纳秒数的组合。Instant 类是不可变的(immutable)。

使用 Instant 类可以方便地进行时间戳的比较、计算和格式化。

只需要获取一个简单的时间戳,而不需要进行更复杂的时间计算和处理,那么可以使用 System.currentTimeMillis() 方法来获取当前时间戳。如果您需要更精确和可靠的时间处理,或者需要涉及时区和日历等问题,那么建议使用 Instant 类来获取时间戳

以下是一些示例:

// 获取当前时间戳:
Instant now = Instant.now();

// 获取指定时间戳:
Instant instant = Instant.ofEpochSecond(epochSecond);

// 将 Instant 对象转换为 Unix 时间戳(秒数):
long epochSecond = instant.getEpochSecond();

// 将 Instant 对象转换为毫秒数:
long millis = instant.toEpochMilli();

// 比较两个 Instant 对象的先后顺序:
int cmp = instant1.compareTo(instant2); // 返回负数、零或正数,表示 instant1 在 instant2 之前、同时或之后
boolean isBefore = instant1.isBefore(instant2);
boolean isAfter = instant1.isAfter(instant2);

// 计算两个 Instant 对象之间的时间间隔(Duration):
Duration duration = Duration.between(instant1, instant2);
long seconds = duration.getSeconds(); // 获取间隔的秒数
long millis = duration.toMillis(); // 获取间隔的毫秒数

// 格式化 Instant 对象:
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
String formatted = formatter.format(instant);

Instant 类是以 UTC 时间为基准的,因此在处理时区和夏令时时需要格外小心。如果需要处理本地时间,可以使用 ZonedDateTime 类

在springboot使用 JDK8 ,针对统计时间等场景,如何使用 Instant 类统计一个接口的运行时间

@RestController
public class MyController {

    private static final Logger log = LoggerFactory.getLogger(MyController.class);

    @GetMapping("/hello")
    public String hello() {
        Instant startTime = Instant.now();

        // 接口方法的业务逻辑

        Instant endTime = Instant.now();
        Duration duration = Duration.between(startTime, endTime);
        long millis = duration.toMillis();
        log.info("接口方法运行时间:{} ms", millis);

        return "Hello, World!";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值