Check if current time is more than an hour from "last_updated" time

10,364

You're going to want to do math between two Calendars or Dates.

Note: Aspects of Date are deprecated, see below for Calendar!

Here's an example using 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;
}

There are some try/catch blocks involved here (which you should probably handle with throws), but this is the basic idea.

Edit: Since parts of Date are deprecated, here is the same method using 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;
}
Share:
10,364
Dave
Author by

Dave

Artist / Designer / Programmer

Updated on June 17, 2022

Comments

  • Dave
    Dave almost 2 years

    On my Android App, I'd like to only re-import my data if it's been at least X hours since the last import.

    I'm storing the last_updated time in my sqlite database in this format: 2012/07/18 00:01:40

    How can I get "hours from then" or something like that?

    My code thus far:

    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;
      }
    
    }