如何解决如何使用Java 8以UTC格式存储DateTime?
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数据时间格式的最佳策略是什么?
解决方法
LocalDateTime
的问题在于它根本不存储偏移量或时区,这意味着您无法将其格式化为包含String
的UTC的Z
分别偏移+00:00
。
我会使用ZonedDateTime
,它会有一个偏移量,并且区域ID和格式使用的是特定的DateTimeFormatter
(不完全知道您的注释将如何处理)。
这是一个简单的Java示例:
public static void main(String[] args) {
// get an example time (the current moment) in UTC
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
// print its toString (implicitly)
System.out.println(now);
// format it using a built-in formatter
System.out.println(now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// or define a formatter yourself and print the ZonedDateTime using that
System.out.println(now.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssz")));
}
这个小例子的输出是(几秒钟前):
2020-10-01T15:06:16.705916600Z
2020-10-01T15:06:16.7059166Z
2020-10-01T15:06:16Z
我认为您可以在@JSONFormat
批注中使用这种模式。不确定,但现在无法查找。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。