简体   繁体   English

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

[英]How to bind date @ConfigurationProperties with time only using @DateTimeFormat?

New to spring-boot. spring-boot 的新功能。

I'm trying to parse the properties from the file with annotation @ConfigurationProperties.我正在尝试使用注释@ConfigurationProperties 解析文件中的属性。 I'm able to parse the fields other than date field.我能够解析日期字段以外的字段。

issue is My property file has only time without date.问题是我的属性文件只有时间没有日期。 ie date=09:30:00.即日期=09:30:00。

I'm able to parse it with @DateTimeFormat(pattern = "HH:mm:ss").我可以用@DateTimeFormat(pattern = "HH:mm:ss") 解析它。 But the issue is, it is giving date as date=Thu Jan 01 09:30:00 GST 1970.但问题是,它给出的日期为 date=Thu Jan 01 09:30:00 GST 1970。

I would like to get the date as todays date with time 09:30:00.我想将日期设为今天的日期,时间为 09:30:00。 Is it possible?可能吗?

@ConfigurationProperties
public class Config {

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

Property财产

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

Why not use a type that represents time only?为什么不使用只代表时间的类型呢?

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

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

The output you are getting is as expected because a string is parsed into java.util.Date using a SimpleDateFormat which defaults the date-time to January 1, 1970, 00:00:00 GMT .您得到的 output 符合预期,因为使用SimpleDateFormat将字符串解析为java.util.Date ,默认日期时间为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);
    }
}

The output in my timezone (Europe/London):我的时区(欧洲/伦敦)中的 output:

Thu Jan 01 09:30:00 GMT 1970

Note that the java.util.Date object is not a real date-time object like the modern date-time types ;请注意, java.util.Date object 不是真正的日期时间 object 像现代日期时间类型 rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC).相反,它表示自称为“纪元”的标准基准时间(即January 1, 1970, 00:00:00 GMT (或 UTC)以来的毫秒数。 When you print an object of java.util.Date , its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value.当您打印 java.util.Date 的java.util.Date时,它的toString方法返回 JVM 时区中的日期时间,这是根据这个毫秒值计算的。 If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.如果您需要在不同的时区打印日期时间,则需要将时区设置为SimpleDateFormat并从中获取格式化字符串。 The java.util date-time API and their formatting API, SimpleDateFormat are not only outdated but also error-prone because of many such things. java.util date-time API 及其格式 API、 SimpleDateFormat不仅过时而且容易出错,因为有很多这样的事情。 It is recommended to stop using them completely and switch to the modern date-time API 1 .建议完全停止使用它们并切换到现代日期时间 API 1

Given below are a couple of options:下面给出了几个选项:

  1. Recommended: Use LocalTime which truly represents time.推荐:使用真正代表时间的LocalTime
    @DateTimeFormat(pattern = "HH:mm:ss")
    private LocalTime time;
  1. Dirty way: Declare your field as a String and parse it in your business logic making it error-prone and dirty.肮脏的方式:将您的字段声明为String并在您的业务逻辑中对其进行解析,使其容易出错且肮脏。
    private String time;

I strongly recommend NOT to go with the second option.我强烈建议不要使用第二个选项 go。

A quick demo using LocalTime :使用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);
    }
}

Output: Output:

09:30
09:30:00

Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time了解有关现代日期时间 API 的更多信息。


1. For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project . 1. For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project .

Don't use old and obsolete class Date.不要使用旧的和过时的 class 日期。 Look into package java.time and in particular in your case - class LocalTime .查看 package java.time ,特别是在您的情况下 - class LocalTime

change your code to: @ConfigurationProperties public class Config {将您的代码更改为:@ConfigurationProperties public class Config {

private int id;

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

} }

This should work.这应该有效。 You may need to add the following dependency:您可能需要添加以下依赖项:

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

This is modified answer from this question: Spring Data JPA - ZonedDateTime format for json serialization这是这个问题的修改答案: Spring Data JPA - ZonedDateTime format for json serialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM