用java编写日期转换器
时间: 2023-11-26 09:06:52 浏览: 28
以下是一个简单的Java程序,可以将日期从一种格式转换为另一种格式:
```java
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter {
public static void main(String[] args) {
String inputDate = "2021-06-01";
String inputFormat = "yyyy-MM-dd";
String outputFormat = "dd/MM/yyyy";
String outputDate = convertDate(inputDate, inputFormat, outputFormat);
System.out.println("Input Date: " + inputDate);
System.out.println("Output Date: " + outputDate);
}
public static String convertDate(String inputDate, String inputFormat, String outputFormat) {
DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
try {
Date date = inputDateFormat.parse(inputDate);
String outputDate = outputDateFormat.format(date);
return outputDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
```
在这个例子中,我们将输入日期“2021-06-01”从格式“yyyy-MM-dd”转换为格式“dd/MM/yyyy”。程序的输出将是:
```
Input Date: 2021-06-01
Output Date: 01/06/2021
```
你可以根据需要更改输入日期、输入格式和输出格式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)