欢迎访问宙启技术站
智能推送

Java函数实现获取当前时间的时间戳

发布时间:2023-10-19 15:14:27

Java提供了获取当前时间的时间戳的函数。以下是几种常见的实现方式:

1. 使用System类的currentTimeMillis()方法:

   long timestamp = System.currentTimeMillis();
   

2. 使用Date类和getTime()方法:

   Date date = new Date();
   long timestamp = date.getTime();
   

3. 使用Calendar类的getTimeInMillis()方法:

   Calendar calendar = Calendar.getInstance();
   long timestamp = calendar.getTimeInMillis();
   

4. 使用Instant类的now()方法:

   Instant instant = Instant.now();
   long timestamp = instant.toEpochMilli();
   

5. 使用LocalDateTime类和Instant类的toEpochMilli()方法:

   LocalDateTime localDateTime = LocalDateTime.now();
   long timestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
   

需要注意的是,toInstant方法需要传入一个ZoneOffset参数,用来确定所在时区的偏移量。

以上是几种常见的获取当前时间戳的实现方式。根据具体业务需求和使用场景的不同,可以选择合适的方式来获取当前时间的时间戳。