调用Java函数以获取当前时间戳。
发布时间:2023-07-03 23:19:13
在Java中,可以使用java.util.Date类或java.time.Instant类来获取当前时间戳。以下是两个方法的示例:
1. 使用java.util.Date类:
import java.util.Date;
public class GetCurrentTimestamp {
public static void main(String[] args) {
// 创建一个Date对象,它表示当前时间
Date currentDate = new Date();
// 获取当前时间的时间戳(以毫秒为单位)
long timestamp = currentDate.getTime();
// 打印当前时间戳
System.out.println("Current Timestamp: " + timestamp);
}
}
以上代码中,首先创建了一个Date对象currentDate,它表示当前时间。然后,通过调用getTime()方法,可以获取currentDate表示的时间的时间戳(以毫秒为单位)。
请注意,Date类的getTime()方法返回的是自1970年1月1日00:00:00以来的毫秒数。
2. 使用java.time.Instant类:
import java.time.Instant;
public class GetCurrentTimestamp {
public static void main(String[] args) {
// 获取当前时间的时间戳
Instant currentTimestamp = Instant.now();
// 打印当前时间戳
System.out.println("Current Timestamp: " + currentTimestamp.toEpochMilli());
}
}
以上代码中,通过调用Instant.now()方法,可以获取当前时间的Instant对象currentTimestamp。然后,通过调用toEpochMilli()方法,可以将currentTimestamp转换为毫秒表示的时间戳。
Instant类是Java 8引入的新的日期和时间API中的一部分。Instant.now()方法返回的是自1970年1月1日00:00:00以来的秒数和纳秒数的组合。
这两种方法都可以用来获取当前的时间戳,可以根据实际需要选择使用哪一种。
