Reputation: 29141
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;
}
}
Upvotes: 4
Views: 11652
Reputation: 23394
You can also do it directly on the query. Look this question, there is examples of how to calculate difference between two dates:
SQLite: express the difference as days, hours, minutes between two given dates
Upvotes: 0
Reputation: 67522
You're going to want to do math between two Calendar
s or Date
s.
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;
}
Upvotes: 9