0

我试图避免重新安装 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

任何人都知道为什么它没有按照我指定的模式给我一个日期?

4

3 回答 3

3

仅包含日期时间的java.sql.Date日期部分。您可能想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. 另请参阅SimpleDateFormatjavadoc

也可以看看:

于 2010-11-09T01:56:42.907 回答
2

java.sql.Date用于指定 toString 方法返回格式为“yyyy-mm-dd”的字符串的 javadocs ,因此您看到了正确的行为。该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));
}
于 2010-11-09T01:51:57.680 回答
0

您是否尝试将 java.sql.Date 更改为 java.util.Date?

于 2010-11-09T01:51:41.467 回答