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

使用Java函数查询当前时间的方法

发布时间:2023-08-31 09:47:18

在Java中,我们可以使用多种方法来查询当前时间。下面我将介绍几种常用的方法。

1. 使用System.currentTimeMillis()方法

System.currentTimeMillis()方法返回当前时间距离1970年1月1日午夜的毫秒数。我们可以使用这个方法来查询当前时间。

public static void getCurrentTime() {
    long currentTimeMillis = System.currentTimeMillis();
    Date currentDate = new Date(currentTimeMillis);
    System.out.println("当前时间是:"+currentDate);
}

2. 使用Date类

Java中的Date类可以表示一个特定的日期和时间。我们可以使用Date类来获取当前日期和时间。

public static void getCurrentTime() {
    Date currentDate = new Date();
    System.out.println("当前时间是:"+currentDate);
}

3. 使用Calendar类

Calendar类是用于处理日期和时间的抽象类。我们可以使用Calendar类来获取当前日期和时间。

public static void getCurrentTime() {
    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    System.out.println("当前时间是:"+currentDate);
}

4. 使用SimpleDateFormat类

SimpleDateFormat类是Java中用于格式化日期和时间的类。我们可以使用SimpleDateFormat类将当前日期和时间格式化为我们想要的形式。

public static void getCurrentTime() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String currentTime = dateFormat.format(new Date());
    System.out.println("当前时间是:"+currentTime);
}

以上是几种常用的方法来查询当前时间的示例代码。你可以根据自己的需求选择合适的方法来使用。