如何在spring boot中更改时间戳的格式

how to change the format of timestamp in springboot

我写了一个这样的控制器,它只是return当前时间戳

@GetMapping(value = "/i/testTime")
Timestamp testTime(HttpServletRequest req) throws IOException {

    return new Timestamp(System.currentTimeMillis());
}

我访问 url 并且它 returns:

"2022-02-25T08:23:32.690+00:00"

有没有办法配置这种格式?

任何答案都会有帮助

我建议使用 java.time 包的 LocalDateTime class。

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);
}

您甚至可以在控制器中没有逻辑的情况下使用注释来完成。

    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());
    }