Home > Software engineering >  how to change the format of timestamp in springboot
how to change the format of timestamp in springboot

Time:02-25

I write a controller like this and it just return the current timestamp

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

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

I access the url and it returns:

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

Is there a way to configure this format?

Any answer will be helpful

CodePudding user response:

I would suggest using java.time package's 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);

Output

Before Formatting: 2017-01-13T17:09:42.411
After Formatting: 13-01-2017 17:09:42

SO in your case, it would be something like this:

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

CodePudding user response:

You can even do it with annotations without having logic in your controller.

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

And your controller like:

    @GetMapping(value = "/i/testTime")
    DateDto testTime(HttpServletRequest req) throws IOException {
        return new DateDto(LocalDateTime.now());
    }
  • Related