簡體   English   中英

如何在 Java 中將字符串解析為日期

[英]How to parse String to Date in Java

我想將字符串24 May 2020 07:40 AM轉換為日期格式Mon May 24 07:40:55 IST 2020 我嘗試使用 Calendar 和 SimpleDateFormatter 但沒有找到解決方案。 任何幫助表示贊賞。

我希望返回類型為Date因為我必須將它與幾個Date進行比較。

java.time

When you've got some Date objects — likely from a legacy API that you cannot afford to upgrade to java.time just now — I still recommend that you use java.time, the modern Java date and time API, for your comparisons.

在以下示例中,我使用來自 java.time 的Instant ,但您也可以使用ZonedDateTime或其他一些現代類型。

    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern("d MMM uuuu hh:mm a", Locale.ENGLISH);

    Date anOldfashionedDate = new Date(1_590_286_000_000L);
    Date anotherOldfashionedDate = new Date(1_590_287_000_000L);
    System.out.println("The Date objects are " + anOldfashionedDate + " and " + anotherOldfashionedDate);

    String aString = "24 May 2020 07:40 AM";

    Instant instantFromDate = anOldfashionedDate.toInstant();
    Instant instantFromAnotherDate = anotherOldfashionedDate.toInstant();
    Instant instantFromString = LocalDateTime.parse(aString, fromFormatter)
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toInstant();

    System.out.println("Comparing " + instantFromDate + " and " + instantFromString + ": "
            + instantFromDate.compareTo(instantFromString));
    System.out.println("Comparing " + instantFromAnotherDate + " and " + instantFromString + ": "
            + instantFromAnotherDate.compareTo(instantFromString));

Output 是(在亞洲/加爾各答時區運行時):

 The Date objects are Sun May 24 07:36:40 IST 2020 and Sun May 24 07:53:20 IST 2020 Comparing 2020-05-24T02:06:40Z and 2020-05-24T02:10:00Z: -1 Comparing 2020-05-24T02:23:20Z and 2020-05-24T02:10:00Z: 1

以 UTC Instant打印; 這是它的toString方法生成的。 尾隨Z表示 UTC。 由於印度標准時間比 UTC 時間早 5 小時 30 分鍾,因此印度的 07:40 AM 與 UTC 的 02:10 時間相同。

鑒於您現在開始使用 java.time,當您的舊 API 也升級到使用 java.time 時,您已做好充分准備。

反向轉換

如果您堅持使用Date來回答您的問題,則相反的轉換也很容易:

    Date oldfashionedDateFromInstantFromString = Date.from(instantFromString);
    System.out.println("Converting to old-fashioned: " + oldfashionedDateFromInstantFromString);

轉換為老式:2020 年 5 月 24 日星期日 07:40:00 IST

關聯

Oracle 教程:日期時間解釋如何使用 java.time。

暫無
暫無

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

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