如何仅使用@DateTimeFormat 将日期@ConfigurationProperties 与时间绑定?

问题描述

spring-boot 新手。

我正在尝试从带有注释@ConfigurationProperties 的文件中解析属性。我能够解析日期字段以外的字段。

问题是我的属性文件只有时间没有日期。即日期=09:30:00。

我可以用@DateTimeFormat(pattern = "HH:mm:ss") 解析它。但问题是,它给出的日期为 date=Thu Jan 01 09:30:00 GST 1970。

我想将日期作为今天的日期,时间为 09:30:00。可能吗?

@ConfigurationProperties
public class Config {

    private int id;
    
    private int version;
        
    @DateTimeFormat(pattern = "HH:mm:ss")
    private Date date;
    
}

财产

id=12
version=2
date=09:30:00

解决方法

为什么不使用只代表时间的类型?

    @DateTimeFormat(pattern = "HH:mm:ss")
    private LocalTime time;

    public LocalDateTime getDate() {
        return LocalDateTime.of(LocalDate.now(),time);
    } 
,

您得到的输出符合预期,因为使用 java.util.Date 将字符串解析为 SimpleDateFormat,默认日期时间为 January 1,1970,00:00:00 GMT

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws ParseException {
        String text = "09:30:00";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date date = sdf.parse(text);
        System.out.println(date);
    }
}

我所在时区(欧洲/伦敦)的输出:

Thu Jan 01 09:30:00 GMT 1970

请注意,java.util.Date 对象不是像 modern date-time types 那样的真实日期时间对象;相反,它表示自称为“纪元”的标准基准时间以来的毫秒数,即 January 1,00:00:00 GMT(或 UTC)。当您打印 java.util.Date 的对象时,它的 toString 方法返回 JVM 时区中的日期时间,从这个毫秒值计算出来。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFormat 并从中获取格式化的字符串。 java.util 日期时间 API 及其格式化 API SimpleDateFormat 不仅过时而且容易出错,因为有很多这样的事情。建议完全停止使用它们并切换到 modern date-time API1

下面给出了几个选项:

  1. 推荐:使用真正代表时间的LocalTime
    @DateTimeFormat(pattern = "HH:mm:ss")
    private LocalTime time;
  1. 肮脏的方式:将您的字段声明为 String 并在您的业务逻辑中对其进行解析,使其容易出错且肮脏。
    private String time;

我强烈建议不要选择第二个选项。

使用 LocalTime 的快速演示:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String text = "9:30:00";

        // The optional part can be put inside square bracket
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("H:m[:s]",Locale.ENGLISH);
        LocalTime time = LocalTime.parse(text,dtfInput);

        // Default implementation of LocalTime#toString omits the seconds part if it is zero
        System.out.println(time);

        // Custom output
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("HH:mm:ss",Locale.ENGLISH);
        String formatted = dtfOutput.format(time);
        System.out.println(formatted);
    }
}

输出:

09:30
09:30:00

Trail: Date Time 了解有关现代日期时间 API 的更多信息。


1。出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。如果您正在工作对于 Android 项目并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

,

不要使用旧的和过时的类 Date。查看包 java.time,特别是在您的情况下 - class LocalTime

将您的代码更改为: @配置属性 公共类配置{

private int id;

private int version;
    
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "HH:mm:ss")
private LocalTime date;

}

这应该有效。您可能需要添加以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.0</version>
</dependency>

这是从这个问题修改后的答案:Spring Data JPA - ZonedDateTime format for json serialization