I have a spring boot application with a receipt entity here I have a LocalDateTime date defined like this:
@Nullable
@Column(name = "date_time")
private LocalDateTime dateTime;
Before saving my entity I am trying to convert the current system date to this format:
dd.MM.yyyy HH:mm:ss
But I am getting a DateTimeParseExcetion with this text:
java.time.format.DateTimeParseException: Text '26.12.2022 13:25:30' could not be parsed at index 0
This is how my code looks:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ROOT);
LocalDateTime now = LocalDateTime.now();
log.debug("REST request to save Receipt : {}", receiptDTO);
if (receiptDTO.getId() != null) {
throw new BadRequestAlertException("A new receipt cannot already have an ID", ENTITY_NAME, "idexists");
}
Optional<User> currentUser = userService.getUserWithAuthoritiesByLogin(SecurityContextHolder.getContext().getAuthentication().getName());
receiptDTO.setDateTime(LocalDateTime.parse(dtf.format(now)));
currentUser.ifPresent(user -> receiptDTO.setUser(this.UserMapper.userToUserDTO(user)));
ReceiptDTO result = receiptService.save(receiptDTO);
UPDATE :
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ROOT);
LocalDateTime now = LocalDateTime.now();
String formattedCurrentTime = dateFormat.format(now);
LocalDateTime localdatetime = LocalDateTime.parse(formattedCurrentTime, dateFormat);
log.debug("REST request to save Receipt : {}", receiptDTO);
if (receiptDTO.getId() != null) {
throw new BadRequestAlertException("A new receipt cannot already have an ID", ENTITY_NAME, "idexists");
}
Optional<User> currentUser = userService.getUserWithAuthoritiesByLogin(SecurityContextHolder.getContext().getAuthentication().getName());
receiptDTO.setDateTime(localdatetime);
UPDATE 2:
COMPLETE METHOD:
@PostMapping("/receipts")
public ResponseEntity<ReceiptDTO> createReceipt(@RequestBody ReceiptDTO receiptDTO) throws URISyntaxException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss", Locale.ENGLISH);
LocalDateTime now = LocalDateTime.now();
String formattedCurrentTime = now.format(formatter);
log.debug("REST request to save Receipt : {}", receiptDTO);
if (receiptDTO.getId() != null) {
throw new BadRequestAlertException("A new receipt cannot already have an ID", ENTITY_NAME, "idexists");
}
receiptDTO.setDateTime(now);
Optional<User> currentUser = userService.getUserWithAuthoritiesByLogin(SecurityContextHolder.getContext().getAuthentication().getName());
currentUser.ifPresent(user -> receiptDTO.setUser(this.UserMapper.userToUserDTO(user)));
ReceiptDTO result = receiptService.save(receiptDTO);
return ResponseEntity
.created(new URI("/api/receipts/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}