簡體   English   中英

如何將日期時間轉換為德語格式

[英]How to convert datetime to german format

我有一個帶有收據實體的 spring 啟動應用程序 我有一個 LocalDateTime 日期定義如下:

@Nullable
@Column(name = "date_time")
private LocalDateTime dateTime;

在保存我的實體之前,我試圖將當前系統日期轉換為這種格式:

dd.MM.yyyy HH:mm:ss

但是我得到一個帶有此文本的 DateTimeParseExcetion:

java.time.format.DateTimeParseException: Text '26.12.2022 13:25:30' could not be parsed at index 0

這是我的代碼的樣子:

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

更新:

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

更新 2:

完整方法:

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

您實際上不需要編寫自己的代碼來格式化 LocalDateTime。 您可以使用以下注釋聲明它:

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

有關更多詳細信息,請查看此處: Spring 數據 JPA - json 序列化的 ZonedDateTime 格式(查看已接受的答案)

來自LocalDateTime的 javadoc:

ISO-8601 日歷系統中沒有時區的日期時間,例如 2007-12-03T10:15:30。

來自LocalDateTime的 toString()

將此日期時間輸出為字符串,例如 2007-12-03T10:15:30。 output 將是以下 ISO-8601 格式之一:(...)

LocalDateTime始終為 output ISO-8601 格式的日期時間。

目前尚不清楚您要做什么,但據我所知,您的目標只是將數據保存在數據庫中。 如果是這種情況,只需按原樣保存日期,然后在檢索時格式化以供展示。 這是您的數據庫的限制嗎(數據庫是否只接受dd.MM.yyyy HH:mm:ss格式的日期)? 如果不是這種情況,那么在堅持之前格式化日期是沒有意義的。 日期格式主要用於演示和應用程序輸入目的。

您似乎對LocalDateTime實例及其文本表示感到困惑。 LocalDateTime (或任何日期時間類型)應該保存有關日期時間單位(例如年、月、日、小時、分鍾等)的信息,以及如何以文本形式打印它取決於您的格式它。 默認文本表示由LocalDateTime#toString返回,例如

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

您代碼中的以下行沒有意義,並且也導致了錯誤:

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

你應該把它簡單地寫成

receiptDTO.setDateTime(now);

錯誤的原因是java.time API 基於ISO 8601 ,並且不需要DateTimeFormatter來解析已經是 ISO 8601 格式的日期時間字符串(例如2022-12-26T13:25 )但是dtf.format(now)返回一個不是 ISO 8601 格式的字符串。

Trail:Date Time了解有關現代日期時間 API 的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM