1. 将时间转化成字符串
Date date = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedTime1 = sdf1.format(date);
System.out.println("格式化后的时间为:" + formattedTime1);
SimpleDateFormat sdf2 = new SimpleDateFormat("EEE MMM dd yyyy hh:mm a zzzz");
String formattedTime2 = sdf2.format(date);
System.out.println("自定义格式化后的时间为:" + formattedTime2);
2 结果展示图片
3. 将字符串转化成时间
String dateTimeStr = "2025-01-09 14:29:59";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date newdate = inputFormat.parse(dateTimeStr);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");
String formattedDateTime = outputFormat.format(newdate);
System.out.println(formattedDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
4 结果展示图片
5. 完整内容实例展示
package com.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class shijianDateTest {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedTime1 = sdf1.format(date);
System.out.println("格式化后的时间为:" + formattedTime1);
SimpleDateFormat sdf2 = new SimpleDateFormat("EEE MMM dd yyyy hh:mm a zzzz");
String formattedTime2 = sdf2.format(date);
System.out.println("自定义格式化后的时间为:" + formattedTime2);
String dateTimeStr = "2025-01-09 14:29:59";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date newdate = inputFormat.parse(dateTimeStr);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");
String formattedDateTime = outputFormat.format(newdate);
System.out.println(formattedDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
6 结果展示图片