0

I'm trying to avoid reinstalling Eclipse to solve this, so I hope someone can help with this date-parsing problem. Here's what I do.

DateFormat dateFormat; 

That's a variable in my class. I set it to the following.

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

When another method is called, I create a new java.sql.Date instance using strings that are passed in. For the sake of clarity, here's a shortened version.

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

When I look at the strings resulting from these operations (just adding .toString() to instantiations above), I get output like the following

2010-10-30
2010-11-29

... instead of the input strings, which are reported to be...

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

Anyone know why it doesn't give me a date in the pattern I specified?

4

3 に答える 3

3

には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. SimpleDateFormatjavadocも参照してください。

以下も参照してください。

于 2010-11-09T01:56:42.907 に答える
2

java.sql.DatetoString メソッドが「yyyy-mm-dd」の形式で文字列を返すことを指定するための javadoc があるため、正しい動作が見られます。オブジェクトは、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 に答える