使用LocalDate进行时间类型格式转换的时候报UnsupportedTemporalTypeException: Unsupported field: HourOfDay错误

10 篇文章 0 订阅

参考博客
https://www.cnblogs.com/krcys/p/9146339.html

在使用java8中的LocalDate进行时间格式化,报了一个异常,代码如下

LocalDate now = LocalDate.now();
String day = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

在执行到String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));抛出异常,错误信息如下:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
	at java.time.LocalDate.get0(LocalDate.java:680)
	at java.time.LocalDate.getLong(LocalDate.java:659)
	at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
	at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540)
	at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
	at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
	at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
	at java.time.LocalDate.format(LocalDate.java:1691)

到jdk源码中查看:

private int get0(TemporalField field) {
    switch ((ChronoField) field) {
        case DAY_OF_WEEK: return getDayOfWeek().getValue();
        case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
        case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;
        case DAY_OF_MONTH: return day;
        case DAY_OF_YEAR: return getDayOfYear();
        case EPOCH_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead");
        case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1;
        case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;
        case MONTH_OF_YEAR: return month;
        case PROLEPTIC_MONTH: throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead");
        case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year);
        case YEAR: return year;
        case ERA: return (year >= 1 ? 1 : 0);
    }
    throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}

说明我在DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")中的的HH:mm:ss是不在case之中的。

原因

因为LocalDate中是不包含时分秒的,想要格式化时分秒需要用LocalDateTime这个类,里边包含的有时分秒

LocalDateTime now = LocalDateTime.now();
String day = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值