Java DateTimeFormatter.parse()的坑

官方文档中,DateTimeFormatter.parse()的返回值类型是TemporalAccessor类型。
但是,运行时的具体类型是:java.time.format.Parsed类型,无法类型转换为java.io下面的时间类。

正确的写法应该是:

import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.LocalDate;
public class Test{
    
    
	public static void main(String[] args){
    
    
		DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
		// 使用对应日期类的from方法获得对应的日期类型
		// 直接转换是无法转换的
		LocalDate date = LocalDate.from(formatter.parse("2021年11月26日"));
	}
}

也可直接使用java.time下每个日期类对应的静态parse方法;

猜你喜欢

转载自blog.csdn.net/D___H/article/details/121479052
今日推荐