How to get the current time and date in java

Use the Date class in java to get the current time and date. The usage is very simple, as follows:

import java.util.Date;

public class test1 {
    public static void main(String[] args) {
        //初始化一个Date类的对象
        Date test_date = new Date();
        //以字符串形式输出当前日期和时间
        System.out.println(test_date.toString());
    }
}

output:

Wed Mar 22 16:36:49 CST 2023

Use the SimpleDateFormat class in java to format time, as follows:

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

public class test1 {
    public static void main(String[] args) {
        //初始化一个Date类的对象
        Date test_date = new Date();
        //根据给定的pattern创建SimpleDateFormat类的对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //输出格式化后的时间
        System.out.println(sdf.format(test_date));
    }
}

output:

2023-03-22 16:40:19

Guess you like

Origin blog.csdn.net/kevinjin2011/article/details/129713394