【发布时间】:2020-10-01 14:49:12
【问题描述】:
Spring Boot 版本2.3.1.
我有以下课程:
@Data
@Entity
@NoArgsConstructor
public class CarParkEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private EventType eventType;
@Column(columnDefinition = "TIMESTAMP")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdAt;
在本地存储事件后,我必须将其发送到后端。 目前,发送数据如下所示:
“createdAt”:“2020-10-01T17:15:23.481”
但是,后端需要以下数据格式:
“createdAt”:“2020-10-01T17:15:23Z”
应用程序的主要思想是向后端发送事件。
所以我需要发送他们期望的确切数据。
看了以下答案后:
- What is this date format? 2011-08-12T20:17:46.384Z
- How to convert LocalDateTime to
“yyyy-MM-dd'T'HH:mm:ss'Z'”format
无法理解我必须如何在本地存储该字段?
我需要转到OffsetDateTime 或ZonedDateTime吗?
另外,我想使用 Java 8 日期时间 API。
要控制日期时间设置,请使用以下实用程序类:
@Slf4j
@UtilityClass
public class TimeClock {
private LocalDateTime dateTime;
public LocalDateTime getCurrentDateTime() {
return (dateTime == null ? LocalDateTime.now() : dateTime);
}
public void setDateTime(LocalDateTime date) {
log.info("Set current date for application to: {}", date);
TimeClock.dateTime = date;
}
public void resetDateTime() {
log.info("Reset date for the application");
TimeClock.dateTime = LocalDateTime.now();
}
/**
* Different formats for current dateTime.
*/
public LocalDate getCurrentDate() {
return getCurrentDateTime().toLocalDate();
}
public LocalTime getCurrentTime() {
return getCurrentDateTime().toLocalTime();
}
}
我在应该创建新日期时间的任何地方都使用它。
使用 Java 8 和 Spring Boot 存储 ISO 8601 数据时间格式的最佳策略是什么?
【问题讨论】:
-
您使用的是哪个数据库?
-
@Eklavya DB 是 MySql。
标签: spring-boot datetime java-8 date-formatting iso8601