我寫了一個這樣的控制器,它只回傳當前時間戳
@GetMapping(value = "/i/testTime")
Timestamp testTime(HttpServletRequest req) throws IOException {
return new Timestamp(System.currentTimeMillis());
}
我訪問 url 并回傳:
"2022-02-25T08:23:32.690 00:00"
有沒有辦法配置這種格式?
任何答案都會有所幫助
uj5u.com熱心網友回復:
我建議使用 java.time 包的 LocalDateTime 類。
LocalDateTime now = LocalDateTime.now();
// LocalDateTime cvDate = Instant.ofEpochMilli(milliseconds).atZone(ZoneId.systemDefault()).toLocalDateTime();
// LocalDateTime utcDate = Instant.ofEpochMilli(milliseconds).atZone(ZoneId.of("UTC")).toLocalDateTime();
System.out.println("Before Formatting: " now);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatDateTime = now.format(format);
輸出
Before Formatting: 2017-01-13T17:09:42.411
After Formatting: 13-01-2017 17:09:42
所以在你的情況下,它會是這樣的:
@GetMapping(value = "/i/testTime")
String testTime(HttpServletRequest req) throws IOException {
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
return currentDateTime.format(format);
}
uj5u.com熱心網友回復:
您甚至可以使用注釋來做到這一點,而無需控制器中的邏輯。
public class DateDto {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private LocalDateTime date;
public DateDto(LocalDateTime date){
this.date = date;
}
public LocalDateTime getDate(){
return this.date;
}
}
你的控制器喜歡:
@GetMapping(value = "/i/testTime")
DateDto testTime(HttpServletRequest req) throws IOException {
return new DateDto(LocalDateTime.now());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432706.html
