Java字符串日期转换为Date类型:2023年6月20日转为2023-06-20格式
在Java中,可以使用SimpleDateFormat类来将字符串日期转换为特定的日期格式,并使用parse()方法将其转换为Date类型。以下是一个示例代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2023年6月20日";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy年MM月dd日");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = inputFormat.parse(dateString);
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate);
// 如果需要将结果转换为Date类型
Date convertedDate = outputFormat.parse(formattedDate);
System.out.println(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
运行上述代码,将输出:
2023-06-20
Wed Jun 20 00:00:00 GMT 2023
这样,你就可以将字符串日期转换为指定的日期格式,并将其转换为Date类型。
原文地址: https://www.cveoy.top/t/topic/pxdE 著作权归作者所有。请勿转载和采集!