Java Date 对象转换为指定日期格式
要将 Java 的 Date 对象转换为指定的日期格式,可以使用 SimpleDateFormat 类。以下是一个示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date currentDate = new Date();
// 定义指定的日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
// 将 Date 对象转换为指定日期格式的字符串
String formattedDate = dateFormat.format(currentDate);
System.out.println('Formatted Date: ' + formattedDate);
}
}
在示例代码中,我们首先创建了一个 Date 对象来表示当前日期和时间。然后,我们使用 SimpleDateFormat 类创建一个指定的日期格式,其中 'yyyy-MM-dd HH:mm:ss' 表示年份-月份-日期 小时:分钟:秒。最后,我们使用 format() 方法将 Date 对象转换为指定日期格式的字符串,并将结果打印出来。
运行示例代码,您将得到类似于以下输出:
Formatted Date: 2022-01-01 12:34:56
原文地址: https://www.cveoy.top/t/topic/o1GL 著作权归作者所有。请勿转载和采集!