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!";
}
}