2017-03-16 11 views
0

Dateオブジェクトで再生するために私のアプリでjoda APIを使用しようとしています。私は次のコード2つのJoda日付の差を秒単位で取得

いくつかの他の活動に今
prefsEdit.putLong(context.getString(R.string.last_status_change_time_key) , DateTime.now().getMillis()); 

を用いsharedpreferencejoda日時を記憶していますいくつかの活動において

、IMこの格納された嗜好をフェッチし、次のコード

long lastStatusChangeTime = objSharedPref.GetAppLongPrefByKey(R.string.last_status_change_time_key); 
DateTime now = DateTime.now(); 
DateTime dateTime = new DateTime(lastStatusChangeTime); 
Seconds seconds = Seconds.secondsBetween(now, dateTime); 
int n = seconds.getSeconds(); 
を使用して日付の間の差を計算します

コードは常にminusの値を返します。たとえば、-31-12などです。

違いが正しく計算されていません。

何が欠けていますか?

secondsBetween()

答えて

1

の宣言がある:

secondsBetween(ReadableInstant start, ReadableInstant end) 

start日付がend日付以前の日付でなければならない肯定結果を得るために。

secondsBetween()は絶対値を返さないためです。あなたの例dateTimeで はnow前に明らかであるので、正の値を取得するために、呼び出しは次のようになります。

Seconds seconds = Seconds.secondsBetween(dateTime, now); 

の代わり:

Seconds seconds = Seconds.secondsBetween(now, dateTime); // <- wrong order as `startDate` parameter is a date after `endDate` parameter 

とあなたのコードは次のようになります。

long lastStatusChangeTime = objSharedPref.GetAppLongPrefByKey(R.string.last_status_change_time_key); 
DateTime now = DateTime.now(); 
DateTime dateTime = new DateTime(lastStatusChangeTime); 
Seconds seconds = Seconds.secondsBetween(dateTime, now); // <-- Here is the difference 
int n = seconds.getSeconds(); 
0

ネイティブJavaコードを使用してください。

long oldTime = Calendar.getInstance().getTime().getTime(); 
Thread.sleep(10*1000); 
long newTime = Calendar.getInstance().getTime().getTime(); 

long diffInMillisecods = newTime - oldTime; 
long diffInSeconds = diffInMillisecods/1000; 
関連する問題