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