通过Java函数获取当前时间戳
发布时间:2023-06-21 09:03:32
Java 中的时间戳是一个长整型数字表示的当前时间的毫秒数,是计算机系统中常用的时间格式之一。在 Java 中获取当前时间戳可以使用 System 类中的 currentTimeMillis() 方法,也可以使用 Java 8 中的新日期时间 API 中的 Instant 类。
1. 使用 System 类中的 currentTimeMillis() 方法
System 类中的 currentTimeMillis() 方法可以获取当前时间的毫秒数,可以通过将其转换为时间戳。以下是使用 currentTimeMillis() 方法获取当前时间戳的代码示例:
long timestamp = System.currentTimeMillis();
System.out.println("当前时间戳:" + timestamp);
输出结果类似于:
当前时间戳:1593591941020
2. 使用 Instant 类
Java 8 中引入了新的日期时间 API,其中 Instant 类提供了获取当前时间戳的方法。以下是使用 Instant 类获取当前时间戳的代码示例:
Instant instant = Instant.now();
long timestamp = instant.toEpochMilli();
System.out.println("当前时间戳:" + timestamp);
输出结果类似于:
当前时间戳:1593591941020
需要注意的是,Instant 类获取的是以 GMT 为标准的时间戳,如果需要转换为本地时间戳,需要使用该 API 的其他方法进行转换。
通过以上两种方法,可以方便地获取当前时间戳。在实际应用中,可能需要将其转换为其他时间格式,也可以根据实际需求进行处理。
