3

私の Android アプリでは、最後のインポートから少なくとも X 時間経過した場合にのみ、データを再インポートしたいと考えています。

last_updated 時刻を sqlite データベースに次の形式で保存しています。 2012/07/18 00:01:40

「それからの時間」などを取得するにはどうすればよいですか?

これまでの私のコード:

package com.sltrib.utilities;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateHelper
{

  public static String now()
  {
      Calendar currentDate = Calendar.getInstance();
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String dateNow = formatter.format(currentDate.getTime());
      //System.out.println("Now the date is :=>  " + dateNow);
      return dateNow;
  }

  public static int hoursAgo(String datetime)
  {
      //return the number of hours it's been since the given time
      //int hours = ??
      //return hours;
  }

}
4

2 に答える 2

9

あなたは2つCalendarのsまたはDatesの間で数学をしたいと思うでしょう。

:のアスペクトDateは非推奨です。以下については以下を参照してくださいCalendar

以下を使用した例を次に示しDateます。

public static int hoursAgo(String datetime) {
    Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime); // Parse into Date object
    Date now = Calendar.getInstance().getTime(); // Get time now
    long differenceInMillis = now.getTime() - date.getTime();
    long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
    return (int)differenceInHours;
}

ここにはいくつかのtry/catchブロックが含まれていますが(おそらくこれを使用して処理する必要がありますthrows)、これが基本的な考え方です。

編集:の一部Dateは非推奨になっているため、以下を使用した同じ方法を次に示しますCalendar

public static int hoursAgo(String datetime) {
    Calendar date = Calendar.getInstance();
    date.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime)); // Parse into Date object
    Calendar now = Calendar.getInstance(); // Get time now
    long differenceInMillis = now.getTimeInMillis() - date.getTimeInMillis();
    long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
    return (int)differenceInHours;
}
于 2012-07-18T00:28:48.137 に答える
0

クエリで直接行うこともできます。この質問を見てください。2 つの日付の差を計算する方法の例があります。

SQLite: 与えられた 2 つの日付の差を日、時間、分で表す

于 2012-07-18T00:35:31.777 に答える