温馨提示×

calendar类如何格式化日期

小樊
150
2024-07-08 11:31:12
栏目: 编程语言

在Java中,可以使用SimpleDateFormat类来格式化日期。以下是一个示例代码:

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

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

在上面的示例中,我们创建了一个SimpleDateFormat对象,并通过指定日期格式“yyyy-MM-dd HH:mm:ss”来格式化当前日期。然后,我们调用format()方法将日期格式化为字符串,并打印出来。

输出将会是类似于以下的格式化日期:

Formatted Date: 2021-07-20 14:30:45

1