【问题标题】:Check if current time is more than an hour from "last_updated" time检查当前时间是否距离“last_updated”时间超过一个小时
【发布时间】:2012-07-18 00:21:03
【问题描述】:

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

}

【问题讨论】:

  • 你可以只以毫秒为单位存储时间。然后你只需要计算差异并将其除以每小时的毫秒数

标签: java android time


【解决方案1】:

您将要在两个 Calendars 或 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;
}

【讨论】:

  • 谢谢 - 我认为这是可行的 - 早上会仔细检查并回复/标记/更新...等
  • 我将其更改为分钟(并与 60 分钟进行比较),因为我不确定 90 分钟是否会返回 1 小时或 2 小时......等等。所以.. 刚刚移除了最后的 60 升,一切顺利 - 它有效!谢谢!
  • 很高兴听到!仅供参考,90 分钟将是 1 小时(由于整数舍入)。但是,如果分钟对您有用,那将是一个完美的解决方案。 :)
  • 当我传递一个字符串时,像下午 05:23,我得到像 400270 这样的大数字???我将其更改为 SimpleDateFormat("hh:mm aa", .... 以匹配我传递的格式。
  • @fullMoon 它很可能认为,由于您没有指定日期,因此您要求的是 1970 年 1 月 1 日下午 5:23...所以 400,000 小时前似乎相当准确。
【解决方案2】:

您也可以直接在查询中执行此操作。看这个问题,有如何计算两个日期之间的差异的例子:

SQLite: express the difference as days, hours, minutes between two given dates

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2012-12-27
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多