簡體   English   中英

為什么SimpleDateFormat無法正確解析我的日期?

[英]Why is SimpleDateFormat not parsing my date correctly?

我試圖避免重新安裝Eclipse來解決此問題 ,因此希望有人可以解決此日期解析問題。 這是我的工作。

DateFormat dateFormat; 

那是我班上的一個變量。 我將其設置為以下內容。

dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// Example input: 2010-11-07 16:00:00

當調用另一個方法時,我使用傳入的字符串創建一個新的java.sql.Date實例。為清楚起見,這是一個簡化的版本。

public void aMethod (String activateTime, String expireTime) {
    Date example = new Date(dateFormat.parse(activateTime).getTime());
    Date example2 = new Date(dateFormat.parse(expireTime).getTime());
}

當我查看這些操作產生的字符串時(只需將.toString()添加到上面的實例化中),我將得到如下所示的輸出

2010-10-30
2010-11-29

...而不是輸入字符串,據報告是...

2010-10-30 17:00:00
2010-11-29 16:00:00

有人知道為什么它沒有按照我指定的方式給我約會嗎?

java.sql.Date僅包含datetime的日期部分。 您可能想改用java.sql.Timestamp

Timestamp example = new Timestamp(dateFormat.parse(activateTime).getTime());
Timestamp example2 = new Timestamp(dateFormat.parse(expireTime).getTime());

它在普通SQL數據庫中的工作方式也是如此。 DATE數據類型僅表示日期, TIME數據類型僅表示時間。 TIMESTAMP數據類型(有時稱為DATETIME )表示日期和時間。

請注意您的小時模式不正確。 在給出的示例中,您希望使用HH而不是hh 另請參見SimpleDateFormat javadoc

也可以看看:

java.sql.Date的javadocs指定toString方法以“ yyyy-mm-dd”格式返回字符串,因此您將看到正確的行為。 Date對象不了解您用來創建它的格式化程序。 要獲得相同格式的輸出,請使用DateFormat.format方法而不是toString

public void aMethod (String activateTime, String expireTime) {
    Date example = new Date(dateFormat.parse(activateTime).getTime());
    Date example2 = new Date(dateFormat.parse(expireTime).getTime());
    System.out.println(example.toString() + " vs " + dateFormat.format(example));
    System.out.println(example2.toString() + " vs " + dateFormat.format(example2));
}

您是否嘗試將java.sql.Date更改為java.util.Date?

暫無
暫無

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

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