import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToStringExample {
public static void main(String[] args) {
// 创建一个Date对象,表示当前时间
Date currentDate = new Date();
// 定义日期格式,例如:"yyyy-MM-dd HH:mm:ss"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将Date对象转换为字符串
String formattedDate = dateFormat.format(currentDate);
// 输出结果
System.out.println("当前日期时间: " + formattedDate);
}
}
Date currentDate = new Date();
:创建一个 Date
对象,表示当前的系统时间。SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
:定义一个 SimpleDateFormat
对象,指定日期和时间的格式。这里使用的是 "yyyy-MM-dd HH:mm:ss"
格式,表示年-月-日 时:分:秒。String formattedDate = dateFormat.format(currentDate);
:使用 SimpleDateFormat
的 format
方法将 Date
对象转换为指定格式的字符串。System.out.println("当前日期时间: " + formattedDate);
:输出转换后的字符串。这个示例展示了如何将 Java 中的 Date
对象转换为指定格式的字符串。
上一篇:在线java编辑器
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站