如何在Spring Boot中正确格式化日期时间?

huangapple go评论74阅读模式
英文:

How to format the date time correctly in Spring Boot?

问题

I would like to know how to format the date time correctly? The result is Localdatetime yyyy-MM-ddTHH:mm.

Could you advise how to solve?

I'm using Java 11, and does it because @JsonFormat not support @RequestParam?

Controller:

@PostMapping("/checkFollowupDate")
public LocalDateTime updateCaseFollowup(@RequestParam("followupDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime followupDate) {
    return followupDate;
}

Entity:

@Entity
@Table(name = "caseFollowup")
public class CaseFollowup {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
    private LocalDateTime followupDate;
}
英文:

I would like to know how to format the date time correctly? The result is Localdatetime yyyy-MM-ddTHH:mm.

Could you advise how to solve?

I'm using Java 11, and does it because @JsonFormat not support @RequestParam?

Controller:

@PostMapping("/checkFollowupDate")
public LocalDateTime updateCaseFollowup(@RequestParam("followupDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime followupDate) {
 return followupDate;
}

Entity:

@Entity
@Table(name = "caseFollowup")
public class CaseFollowup {
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
    private LocalDateTime followupDate;

答案1

得分: 3

由于您正在使用Spring Boot,我也假设您正在使用Java 8。无论如何,请尝试使用Java 8的时间API来处理日期,例如:

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime followupDate;

如果您使用的是早于Java 8发布的JPA 2.1,那么在您的实体类中,您可以使用转换器将其转换为SQL时间戳,如下所示:

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
     
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }
 
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

请注意,在更新的Hibernate版本(Hibernate 5)和JPA中,上述转换将自动执行,不需要提供上述方法。

如果您的要求只是将从@RequestParam读取的日期以特定格式保存到实体类中,您可以在将其设置到实体类之前手动将其转换为任何您选择的格式,例如:

@PostMapping("/caseFollowup")
public Integer updateCaseFollowup(@RequestParam("followupDate") LocalDateTime followupDate) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formatDateTime = followupDate.format(formatter);
}
英文:

Since you are using Spring-boot , I'm also assuming you are using java8 . In any case try using java8 time api for date like :

@JsonFormat(pattern=&quot;yyyy-MM-dd HH:mm:ss&quot;)
private LocalDateTime followupDate;

and if you are on JPA 2.1 which was released before java8 then in your entity class you could have a converter to convert it for sql timestamp like :

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter&lt;LocalDateTime, Timestamp&gt; {
     
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }
 
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

Remember that in newer version of Hibernate(Hibernate 5) and JPA the above conversion will be performed automatically and doesn't require you to provide the above method.

If your requirement is just to persist the Date read from the @RequestParam through the entity class in a particular format, you could always convert it manually into any format that you may choose before setting the value into your entity class like :

@PostMapping(&quot;/caseFollowup&quot;)
    public Integer updateCaseFollowup(@RequestParam(&quot;followupDate&quot;)
                                       LocalDateTime followupDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;);
String formatDateTime = followupDate.format(formatter);

}

答案2

得分: 0

请在您的模型类中使用以下代码:

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ", shape = JsonFormat.Shape.STRING)
private OffsetDateTime lastModifiedDate;

并创建以下类映射器:

import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import org.springframework.stereotype.Component;

@Component
public class DateMapper {
    
    public OffsetDateTime asOffsetDateTime(Timestamp ts) {
        if (ts != null) {
            return OffsetDateTime.of(ts.toLocalDateTime().getYear(), ts.toLocalDateTime().getMonthValue(),
                    ts.toLocalDateTime().getDayOfMonth(), ts.toLocalDateTime().getHour(), ts.toLocalDateTime().getMinute(),
                    ts.toLocalDateTime().getSecond(), ts.toLocalDateTime().getNano(), ZoneOffset.UTC);
        } else {
            return null;
        }
    }

    public Timestamp asTimestamp(OffsetDateTime offsetDateTime) {
        if (offsetDateTime != null) {
            return Timestamp.valueOf(offsetDateTime.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
        } else {
            return null;
        }
    }
}
英文:

use this code in you model class :
<br>

@JsonFormat(pattern = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ssZ&quot;, shape = JsonFormat.Shape.STRING)
        private OffsetDateTime lastModifiedDate;

<br>
and create this class mapper :
<br><br>

import java.sql.Timestamp;
        import java.time.OffsetDateTime;
        import java.time.ZoneOffset;
        @Component
        public class DateMapper {
        
            public OffsetDateTime asOffsetDateTime(Timestamp ts){
                if (ts != null){
                    return OffsetDateTime.of(ts.toLocalDateTime().getYear(), ts.toLocalDateTime().getMonthValue(),
                            ts.toLocalDateTime().getDayOfMonth(), ts.toLocalDateTime().getHour(), ts.toLocalDateTime().getMinute(),
                            ts.toLocalDateTime().getSecond(), ts.toLocalDateTime().getNano(), ZoneOffset.UTC);
                } else {
                    return null;
                }
            }
        
            public Timestamp asTimestamp(OffsetDateTime offsetDateTime){
                if(offsetDateTime != null) {
                    return Timestamp.valueOf(offsetDateTime.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
                } else {
                    return null;
                }
            }
        }

huangapple
  • 本文由 发表于 2020年8月6日 14:53:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63278298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定