我有一个简单的问题,我有下面的函数,上面有调用cacheTime的参数,我如何将它设置为4小时,我应该将它设置为4 * 3600000吗?
public static File getCache(String name, Context c, int cacheTime)
{
if (cacheTime <= 0)
return null;
File cache = new File(c.getCacheDir(), name);
long now = System.currentTimeMillis();
if (cache.exists() && (now - cache.lastModified() < cacheTime))
return cache;
return null;
}发布于 2013-02-16 05:50:53
毫秒是1/1000秒。因此,4小时将是4* 60 * 60 * 1000 = 14,400,000
对于缓存无效,这可能是很好的。也就是说,日期数学通常是危险的。当处理比毫秒更大的时间单位时,很容易在夏令时转换、闰秒和日历要处理的所有其他事情中出错。在某些情况下,这种罕见的不精确是可以接受的,而在另一些情况下,它是不能接受的。在做日期计算时要小心。
要以更大的时间单位(如+1天)确定人类可消耗的时间,请使用Calendar.roll()。
发布于 2013-02-16 05:51:52
学习使用方便的TimeUnit枚举,这样您就可以这样做:
TimeUnit.Hours.toMillis(4)而不是依赖餐巾数学和魔术数字遍布你的代码。
发布于 2013-02-16 05:48:12
// 4 hours * 60 (min/hour) * 60 (sec/min) * 1000 (msec/sec)
getCache(name, c, 4 * 3600 * 1000);https://stackoverflow.com/questions/14903806
复制相似问题