Home > Net >  How to convert datetime to german format
How to convert datetime to german format

Time:12-26

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

CodePudding user response:

You don't really need to write your own code to format your LocalDateTime. You can declare it with the following annotation:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy HH:mm:ss")
@Nullable
@Column(name = "date_time")
private LocalDateTime dateTime;

For more details look here: Spring Data JPA - ZonedDateTime format for json serialization (Look at the accepted answer)

CodePudding user response:

From LocalDateTime's javadoc:

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

From LocalDateTime's toString()

Outputs this date-time as a String, such as 2007-12-03T10:15:30. The output will be one of the following ISO-8601 formats: (...)

The LocalDateTime will always output date times in the ISO-8601 format.

It's not clear what you're trying to do, but, as far as I can see, your goal is simply to save the data in the database. If that's the case, just save the date the way it is and then format at retrieval for presentation. Is this a limitation of your database (does the database only accept dates in the dd.MM.yyyy HH:mm:ss format)? If that's not the case, then there's no sense in formating the date before persisting. Date formats are mainly used for presentation and application input purposes.

CodePudding user response:

You seem to be confused between the LocalDateTime instance and its textual representation. A LocalDateTime (or any date-time type) is supposed to hold the information about the date-time units (e.g. year, month, day, hour, minute etc.), and how you print it in textual form depends on how you format it. The default textual representation is as returned by LocalDateTime#toString e.g.

class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now); // This prints the value of now.toString()

        // An example of textual representation in a custom format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss", Locale.ENGLISH);
        String formatted = now.format(formatter);
        System.out.println(formatted);
    }
}

Output:

2022-12-26T13:20:24.257472
26.12.2022 13:20:24

The following line in your code does not make sense, and has also caused the error:

receiptDTO.setDateTime(LocalDateTime.parse(dtf.format(now)));

You should have written it simply as

receiptDTO.setDateTime(now);

The reason for the error is that the java.time API is based on ISO 8601, and does not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. 2022-12-26T13:25) but dtf.format(now) returns a string which is not in ISO 8601 format.

Learn more about the modern Date-Time API from Trail: Date Time.

  • Related