写一个Java函数来获取系统当前时间
发布时间:2023-10-24 13:26:44
要获取系统当前时间,可以使用Java中的Date类。
import java.util.Date;
public class GetCurrentTime {
public static void main(String[] args) {
Date currentTime = getCurrentTime();
System.out.println("当前时间为:" + currentTime);
}
public static Date getCurrentTime() {
return new Date();
}
}
这段代码定义了一个名为GetCurrentTime的类,其中包含了两个方法:main方法和getCurrentTime方法。
在main方法中,首先调用了getCurrentTime方法来获取当前时间,并将返回的时间对象赋值给currentTime变量。然后使用System.out.println方法将当前时间打印到控制台上。
getCurrentTime方法中,通过创建一个新的Date对象来获取当前时间,并将其返回。Date类是Java中用于表示日期和时间的类,它的构造函数可以不传递任何参数,这时它会获取系统当前时间。
通过运行这段代码,你可以获得系统当前时间。请注意,由于时间的显示格式是计算机内部的表示方式,不同的操作系统和区域设置可能会导致输出的时间格式不同。如果你需要特定格式的时间,可以使用Java中的SimpleDateFormat类来进行格式化。
