用DateTimeFormatter写
时间: 2023-11-07 17:53:10 浏览: 44
当使用Java 8及以上版本时,我们可以使用`DateTimeFormatter`类来进行日期格式化和解析。下面是使用`DateTimeFormatter`类将时间字符串"2022年至8月11日"转换为"yyyy-MM-dd"格式的示例代码:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
String input = "2022年至8月11日";
String outputPattern = "yyyy-MM-dd";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy'年'至M'月'dd'日'");
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern(outputPattern);
try {
LocalDate date = LocalDate.parse(input, inputFormat);
String output = outputFormat.format(date);
System.out.println(output);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先定义了输入字符串`input`和输出日期格式的模式`outputPattern`。然后,我们创建了两个`DateTimeFormatter`对象,一个用于解析输入字符串,另一个用于格式化输出日期。
通过调用`LocalDate.parse(input, inputFormat)`方法,我们将输入字符串解析为一个`LocalDate`对象。然后,我们使用`outputFormat.format(date)`方法将日期对象格式化为指定的输出模式。最后,我们打印输出结果。
运行以上代码,您将得到输出:2022-08-11,即将时间字符串成功转换为了"yyyy-MM-dd"的格式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)