如何使用Java打印当前时间

在Java中,我们可以使用java.util.Date类和SimpleDateFormat类来获取并格式化当前时间。下面将介绍一种简单的方法来打印当前时间。

1. 使用Date类获取当前时间

首先,我们需要使用java.util.Date类来获取当前时间。Date类表示特定的瞬间,精确到毫秒。我们可以使用Date类的getTime()方法获取当前时间的毫秒数,然后通过System.currentTimeMillis()方法将其转换为当前时间。

import java.util.Date;

public class CurrentTimeExample {
    public static void main(String[] args) {
        Date currentTime = new Date();
        System.out.println("Current time: " + currentTime);
    }
}

2. 使用SimpleDateFormat类格式化时间

虽然上面的代码可以打印当前时间,但通常我们希望将时间格式化为特定的格式,比如"yyyy-MM-dd HH:mm:ss"。这时我们可以使用SimpleDateFormat类来格式化时间。

import java.util.Date;
import java.text.SimpleDateFormat;

public class FormattedCurrentTimeExample {
    public static void main(String[] args) {
        Date currentTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedTime = sdf.format(currentTime);
        System.out.println("Formatted current time: " + formattedTime);
    }
}

通过上面的代码,我们可以将当前时间格式化为"yyyy-MM-dd HH:mm:ss"的格式。

类图

classDiagram
    class Date {
        +Date()
        +long getTime()
    }

    class SimpleDateFormat {
        +SimpleDateFormat(String pattern)
        +String format(Date date)
    }

    class CurrentTimeExample {
        +main(String[] args)
    }

    class FormattedCurrentTimeExample {
        +main(String[] args)
    }

3. 结论

通过上面的介绍,我们学习了如何使用Java来打印当前时间。首先,我们使用Date类获取当前时间,然后使用SimpleDateFormat类将时间格式化为需要的格式。这种方法简单、易懂,可以满足我们大部分获取当前时间的需求。希望本文对你有所帮助!