【问题标题】:What's wrong with this localtime in ThymeleafThymeleaf 的这个当地时间有什么问题
【发布时间】:2021-03-27 20:33:22
【问题描述】:

Spring + Thymeleaf 项目的本质描述如下:

@Entity
public class CarEntity {
...
    @Column(name = "time_oot", nullable = false)
    //@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "hh:mm:ss")
    //@DateTimeFormat(pattern = "hh:mm:ss")

    private LocalTime timeOut;
}

我们从 HTML 表单中读取本地时间格式的时间。我没有几秒钟就得到了输出,一切正常。即表单输入属于这种类型:

<label for="inputime">Время</label>
<input type="time" class="form-control" id="inputime" placeholder="Задайте время" max="0:50:00" min="0:00:01" value="00:00" th:field="*{timeOut}" required>

但我不需要表格上的小时,只需要分钟和秒,我在表格上添加了秒:

<label for="inputime">Время</label>
<input type="time" class="form-control" id="inputime" placeholder="Задайте время" max="0:50:00" min="0:00:01" value="00:00:00" step="1" th:field="*{timeOut}" required>

现在错误开始飞出:

Field error in object 'CarEntity' on field 'timeOut': rejected value [00:12:25]; 
codes 
[typeMismatch.CarEntity.timeOut,typeMismatch.timeOut,typeMismatch.java.time.LocalTime,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [CarEntity.timeOut,timeOut]; 
arguments []; default message [timeOut]]; 
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalTime' for property 'timeOut'; 
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] 
to type [@javax.persistence.Column java.time.LocalTime] for value '00:12:25'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [00:12:25]]]

有什么问题?

我尝试添加:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "hh:mm:ss")

@DateTimeFormat(pattern = "hh:mm:ss")

错误仍然崩溃:

"Parse attempt failed for value [01:11:23]"

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    使用@DateTimeFormat(pattern = "HH:mm:ss")

    你可以通过这个来测试:

    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    
    public class Test {
        public static void main(String[] args) {
            LocalTime localTime = LocalTime.parse("00:12:25", DateTimeFormatter.ofPattern("HH:mm:ss"));
            System.out.println("localTime = " + localTime);
        }
    }
    

    当使用hh:mm:ss 时,此代码会抛出异常,当使用HH:mm:ss 时它可以工作。 HH 是您需要使用的 24 小时符号。

    【讨论】:

    • 但我只需要 mm:ss。我不需要hh:mm。我该怎么做呢?或者这个问题不能通过常规手段解决吗?
    • LocalTime 是一个代表小时、分钟和秒的对象。也许你需要Duration 代替?
    • 对我来说最重要的是有几秒钟。无论如何。
    • 在输入表单上,用户必须输入以分和秒为单位的时间。时钟将始终设置为 0。
    • 根据stackoverflow.com/questions/60065890/html5-input-type-duration,HTML 输入可能会显示 AM/PM 指示。您可以做的是使用使用String timeOutCarFormData 对象,并在将CarFormData 转换为实际的CarEntity 时将String 转换为Duration(并使用HTML 中的标准文本输入)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多