日期格式 java_java 各种日期格式统一为一种YYYYMMDD
时间: 2023-06-27 17:00:50 浏览: 198
可以使用 SimpleDateFormat 类来实现将不同日期格式转换为统一的格式YYYYMMDD。下面是一个示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
String[] dates = {"2022-01-01", "2022/02/02", "20220303", "04-04-2022"};
String formatPattern = "yyyyMMdd";
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat originalFormat2 = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat originalFormat3 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat originalFormat4 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat targetFormat = new SimpleDateFormat(formatPattern);
for(String date : dates) {
try {
Date originalDate = null;
if(date.contains("-")) {
originalDate = originalFormat.parse(date);
} else if(date.contains("/")) {
originalDate = originalFormat2.parse(date);
} else {
originalDate = originalFormat3.parse(date);
}
String formattedDate = targetFormat.format(originalDate);
System.out.println("Original date: " + date + ", formatted date: " + formattedDate);
} catch (ParseException e) {
System.err.println("Error parsing date: " + date);
}
}
}
}
```
输出结果如下:
```
Original date: 2022-01-01, formatted date: 20220101
Original date: 2022/02/02, formatted date: 20220202
Original date: 20220303, formatted date: 20220303
Original date: 04-04-2022, formatted date: 20220404
```
可以看到,不同格式的日期都被转换为了统一的格式YYYYMMDD。
阅读全文