2012-07-18 353 views
3

在我的Android应用程序中,如果自上次导入至少X小时后才重新导入数据,检查当前时间距“last_updated”时间是否超过一个小时

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

} 
+0

你可以只保存在毫秒的时间。然后,你只需要计算差异,并以每小时毫秒数为单位来划分它 – Weeman 2012-07-18 00:32:52

回答

6

你会想两个Calendar S或Date S之间做数学。

注意:不推荐使用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; 
} 
+0

对不起,应该是'getTime()';我已更正上述帖子。 – Eric 2012-07-18 00:32:21

+0

谢谢 - 我认为这是行之有效的 - 将在早上复查,并回复/标记/更新...等 – Dave 2012-07-18 02:14:29

+0

我改变它为分钟(和60比较),因为我不确定90分钟是否会返回1或2小时...等。所以..刚刚删除了最后的60L和好去 - 它的作品!谢谢! – Dave 2012-07-18 02:35:16

相关问题