我有一個使用這樣的物體的spring應用程式:
@Getter
@Setter
class Entity {
private Date delay;
}
我將以下 json 傳遞給 spring 端點。
{
"delay": "2022-05-15"
}
當我打電話時,entity.getDelay().getTime()
我得到1652572800
這是過去的日期加上 2 小時。
我想接收 0 小時的日期,因為我需要將該值與資料庫中存盤的沒有小時和分鐘的值進行比較。
我知道如何實作這一目標嗎?
uj5u.com熱心網友回復:
Java 8 帶來了很多語言改進。其中之一是新的 Java 日期和時間 API。新的日期和時間 API 已移至 java.time 包。新的 java.time 包包含日期、時間、日期/時間、時區、瞬間、持續時間和時鐘操作的所有類。
示例類:
- 鐘
- 本地日期
- 語言環境時間
- 本地日期時間
- 期間
使用 LocalDate 的示例
public class YourDto {
private LocalDate delay;
........//todo
}
如下所示查找您的日、年和月
//Using LocalDate
// Month value
(dto.getDelay().getMonth().getValue()); == 5
// Month
(dto.getDelay().getMonth()); == May
// Day
(dto.getDelay().getDayOfMonth()); == 15
// Year
(dto.getDelay().getYear()); == 2022
// Date
(dto.getDelay()); == 2022-05-15
將 LocalDate 轉換為毫秒,反之亦然
// Convert LocalDate to Milliseconds
long time = dto.getDelay().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
System.out.println("Time in millisecoinds = " time);
// Convert Milliseconds to LocalDate
LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(time).toDays());
System.out.println("LocalDate = " myDate);
根據@Ole VV的建議。
// Convert Milliseconds to LocalDate
LocalDate myDate = Instant.ofEpochMilli(time).atOffset(ZoneOffset.UTC).toLocalDate();
UTC 不是時區,而是作為全球民用時間和時區基礎的時間標準。
參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470369.html