[Java] 使用DateTimeFormatterBuilder 解析日期字串


Posted by yaweichiang on 2022-11-26

在後端呼叫第三方API時取得的日期時間字串格式如下:/Date(xxxxxxxxxxxxx+xxxx)/
需要將日期時間字串轉換成以下格式:yyyy-MM-ddTHH:mm:ss

使用DateTimeFormatterBuilder建立符合原始字串的Formatter,用來將原始字串parse成相應LocalDateTime物件
再將LocalDateTime物件透過目標格式的Formatter格式化成我們所想要的日期時間格式字串

DateTimeFormatter jsonDateTimeFormatter = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS)
                .appendValue(ChronoField.MILLI_OF_SECOND,3)
                .appendOffset("+HHmm","+0000")
                .appendLiteral(")/")
                .toFormatter();

DateTimeFormatter targetDateTimeFormatter = DateTiemFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
@JsonProperty("startDate")
private String startDate;

public void setStartDate(String startDate){
    if(startDate.matches("^\\/Date\\(\\d{13,13}\\+\\d{4,4}\\)\\/$")){
        LocalDatetime dateTime = LocalDateTime.parse(startDate,jsonDateTimeFormatter);
        startDate = dateTime.format(targetDateTimeFormatter);
    }
    this.startDate = startDate;
}

#java #DateTimeFormat #JsonDate







Related Posts

[C#] PdfTemplate.iTextSharp.LGPLv2 產生Pdf 範例

[C#] PdfTemplate.iTextSharp.LGPLv2 產生Pdf 範例

網路操作指令與工具:curl, ping, telnet, nslookup

網路操作指令與工具:curl, ping, telnet, nslookup

如何使用 Python 和 Locust 進行 Load testing 入門教學

如何使用 Python 和 Locust 進行 Load testing 入門教學


Comments