0

2 つの日付の差を取得しようとしていますが、文字列を日付に変換することに行き詰まっています。

私のコードは次のとおりです。

    //create a date send it to the database as string
     Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
     SaveToDB(currentDate.ToString());

ある時点で、データベースから日付を取得しようとしています:

       String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
       Date currentDate = new Date();

       //now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception 

       Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception

       long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?

正しい解決策を教えてください。

残念ながら、データベースからの日付は文字列として取得され、それを別の型に変更することはできません。そのため、その文字列を Date() に変換する必要があります。

編集:

例外は:

java.text.ParseException: Format.parseObject(String) failed
    at java.text.Format.parseObject(Unknown Source)
    at main.Program.main(Program.java:20)
4

2 に答える 2

2

Java でのデータと時間関連の操作にはJoda Time API を使用することをお勧めします。この API を使用すると、処理timezoneと関連するすべての変換のニュアンスが非常に簡単になります。

于 2012-09-01T07:45:30.397 に答える
0

受信する文字列形式に一致するように DateFormat を指定する必要があります

例えば。

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));

必要な形式で両方の日付を取得したら、日付算術演算を適用します

DateString のその他の書式指定子は、 http: //docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html にあります。

于 2012-09-01T07:42:59.063 に答える