java - 检查当前时间是否距离 "last_updated"时间超过一个小时

标签 java android time

在我的 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;
  }

}

最佳答案

您将要在两个 CalendarDate 之间进行数学计算。

注意: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 block (您可能应该用 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;
}

关于java - 检查当前时间是否距离 "last_updated"时间超过一个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532676/

相关文章:

JAVA:如何根据字段对列表进行排序

jQuery 时间格式插件

java - 在 REST/Java 中,如果我的对象为 null,我应该返回什么?

java - 读取 persistence.xml 文件中的环境变量

android - 无法在 Anko 中预览

linux - 如何减慢过程的所有时间测量?

java - 即使测试失败,Gradle 也会在测试阶段后执行任务

java - 如何克隆ArrayList并克隆其内容?

android - 具有自定义 BaseAdapter 的可滚动 ListView 非常慢

android - 飞溅 Activity 期间数据库加载缓慢