Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to change the format of timestamp in springboot

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any answer will be helpful

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading