Java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Hours报错解决

Posted Adorable_Rocy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Hours报错解决相关的知识,希望对你有一定的参考价值。

原因分析:

出现这个问题一开始小编还是懵的,在正常情况下使用年月日没出现问题,但是在使用时分秒的时候,就出现了这个问题.

1. 于是小编发现这个问题可能关系到时间的解析

在计算时间的时候使用的是LocalDate类,LocalDate类中解析格式是"yyyy-MM-dd" ,其中是没有时分秒解析的,小编错用了LocalDate类解析时间。

错误使用:

HOURS.between(LocalDate.of(startYear, startMonth, startDay), LocalDate.of(lastYaer, lastMonth, lastDay))

报错如下:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Hours
	at java.time.LocalDate.until(LocalDate.java:1614)
	at java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
	at fatcats.top.utils.CustomDateUtils.diffHoursTime(CustomDateUtils.java:123)
	at fatcats.top.Main.main(Main.java:60)

补充:对于小时的计算,应该使用提供年月日小时的计算方法类LocalDateTime ,它是LocalDate + LocalTime的整合,表示年月日时分秒

2. 举例说明(计算某一天到当前时间的小时数有多少)

   //计算小时
    public static long diffHoursToNow(int startYear,int startMonth , int startDay){
        return HOURS.between(LocalDateTime.of(startYear, startMonth, startDay,0,0,0), LocalDateTime.now());
    }

传入2021.1.1 到至今(5-7 9:40)控制台输出如下:

202111日至今已经过小时:3057小时

完美解决

以上是关于Java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Hours报错解决的主要内容,如果未能解决你的问题,请参考以下文章