import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
// 定义输入的日期字符串和目标格式
String inputDateStr = "2023-10-05";
String inputDateFormat = "yyyy-MM-dd";
String outputDateFormat = "dd/MM/yyyy";
// 创建SimpleDateFormat对象用于解析和格式化日期
SimpleDateFormat inputSdf = new SimpleDateFormat(inputDateFormat);
SimpleDateFormat outputSdf = new SimpleDateFormat(outputDateFormat);
try {
// 将输入的日期字符串解析为Date对象
Date date = inputSdf.parse(inputDateStr);
// 将Date对象格式化为目标格式的字符串
String formattedDate = outputSdf.format(date);
// 输出转换后的日期字符串
System.out.println("Original Date: " + inputDateStr);
System.out.println("Formatted Date: " + formattedDate);
} catch (ParseException e) {
// 捕获解析异常并打印错误信息
System.out.println("Error parsing date: " + e.getMessage());
}
}
}
java.text.ParseException、java.text.SimpleDateFormat和java.util.Date,这些类用于处理日期的解析和格式化。SimpleDateFormat来指定输入日期字符串的格式(如"yyyy-MM-dd")和目标格式(如"dd/MM/yyyy")。inputSdf.parse(inputDateStr)将输入的日期字符串解析为Date对象。outputSdf.format(date)将Date对象格式化为目标格式的字符串。ParseException异常,以确保程序在遇到无效日期字符串时不会崩溃,并打印出错误信息。这段代码展示了如何将一个日期字符串从一种格式转换为另一种格式。
下一篇:java遍历set集合
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站