簡體   English   中英

如何將時間戳字符串格式化為 Java 中的 Date 對象?

[英]How do you format a timestamp string to a Date object in Java?

我正在使用 Spring 框架在 Java 中創建 Web 服務。 它接收帶有參數“payer”、“points”和“timestamp”的 HTTP 請求。

我需要將數據對象存儲在列表中並按時間戳對列表進行排序,因此我試圖將時間戳字符串轉換為 Date 對象。 這是我當前的代碼:

String[] payers; // stores all payers
int totalPayers = 0; // number of payers in 'payers'

@GetMapping("/transaction")
    public void addTrans(@RequestParam(value="payer") String payer, @RequestParam(value="points") int points, @RequestParam(value="timestamp") String time) throws Exception{

        Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(time);
        
        Transaction newTrans = new Transaction(timestamp, payer, points);
        totalTrans++;

        // if the payer is new, add them to the payers list
        boolean newPayer = true;
        for(int i = 0; i < totalPayers; i++){
            if (payer == payers[i]){
                newPayer = false;
                break;
            }
        }
        if(newPayer){
            payers[totalPayers++] = payer;
        }

        transactions.add(newTrans); // add the new transaction to the list
        totalPoints += newTrans.getPoints();

        Collections.sort(transactions); // sort the list by timestamp

        return;
    }

當我運行它時,我收到錯誤:

java.text.ParseException:無法解析的日期:“2020-11-02T14:00:00Z”

有誰知道我可能會丟失的東西? 有沒有更簡單的方法來轉換字符串?

您也需要在Z周圍加上單引號。

Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(time);

Z 不是函數應該識別的模式的一部分。

避免遺留的日期時間類

您正在使用糟糕的日期時間類,這些類在幾年前被 JSR 310 中定義的現代java.time類所取代。切勿使用DateSimpleDateFormat等。

java.time

您的輸入格式符合java.time類中默認使用的ISO 8601標准。 所以不需要指定格式模式。

T將日期部分與時間部分分開。 最后的Z告訴您日期和時間是一個時刻,與 UTC 的偏移量為零時分秒。 根據航空和軍事公約, Z發音為“Zulu”。

以標准 ISO 8601 格式解析文本:

String input = "2022-01-23T12:34:56Z" ;
Instant instant = Instant.now( input ) ;

生成標准 ISO 8601 格式的文本:

String output = instant.toString() ; 

如果您使用的是 java 8 或更高版本,建議使用java.time ( https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html ) 而不是java.util.Date

但是,如果您真的想使用 Date,下面的代碼片段應該可以幫助您解決錯誤並解析字符串。 小心區域計算。

Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse(time);

如果您決定切換到java.time ,下面的代碼片段會有所幫助

Instant instant = Instant.parse(time) ;
Date date = java.util.Date.from(instant);

暫無
暫無

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

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