我一直试图让这个工作好几天,我正在扯掉我的头发。我想我只需要另一双眼睛来帮助我。
我将“条目”存储在数据库中,每个条目在输入时都有一个 Unix 时间戳。我有一个系统,用户可以选择任何日期并查看同一周存储的条目。当我让用户设置一个自定义的一周的第一天并且Calendar.setFirstDayOfWeek().
我永远无法从数据库中获得正确的返回值时,问题出现了周二)。
public void getEntries() {
/* Make sure temp Calendar has same first day */
temp = Calendar.getInstance();
temp.setFirstDayOfWeek(date.getFirstDayOfWeek());
/* Common date ranges in unix time */
long oneday = 86400000L;
long oneweek = 604800000L;
long onemonth = 2628000000L;
long oneyear = 31536000000L;
/* The custom date in unix time. For example, the user may have selected Dec. 1, 2012 */
long set_time = date.getTimeInMillis();
entries.clear();
dba.open();
/* This query gets entries within 1 week and 1 day of the user-set date just to be safe */
Cursor cc = dba.query("Date < " +(set_time+oneweek+oneday)+ " AND Date > " +(set_time-oneday-oneweek));
if(cc.moveToFirst()) do {
/* Set temp calendar to the timestamp of the entry in database */
long unix = cc.getLong(1);
temp.setTimeInMillis(unix);
System.out.println("Temp calendar set to "+temp.getTime().toGMTString()+ " fdow("+temp.getFirstDayOfWeek()+") week("+temp.get(Calendar.WEEK_OF_YEAR)+"), user calendar set to "+date.getTime().toGMTString()+" fdow("+date.getFirstDayOfWeek()+") week("+date.get(Calendar.WEEK_OF_YEAR)+")");
if(temp.get(Calendar.WEEK_OF_YEAR) == date.get(Calendar.WEEK_OF_YEAR)
&& temp.get(Calendar.YEAR) == date.get(Calendar.YEAR) )
/* Entry object is instantiated and added to ArrayList if WEEK_OF_YEAR in temp calendar matches WEEK_OF_YEAR in global calendar */
entries.add(createEntryFromCursor(cc));
} while(cc.moveToNext());
}
在我的测试中,我知道在 2012 年 11 月 30 日有一个条目。将一周的第一天设置为星期二(并且条目是在星期五),如果用户将日期设置为,这应该返回 1 个结果12 月 1 日,如果用户设置为 11 月 26 日(星期一),则没有结果。但是,我得到 1 个结果。怎么了?!
编辑
我还是真的需要帮助!我已经用我当前的代码更新了上面的内容。我仍然得到奇怪的结果。例如,一周的第一天是星期一,我从以下渠道得到System.out
:
12-09 11:46:38.465: I/System.out(15130): Temp calendar set to 9 Dec 2012 19:29:59 GMT fdow(2) week(49), user calendar set to 9 Dec 2012 14:51:59 GMT fdow(2) week(50)
这就是说 2012 年 12 月 9 日发生在 2 个不同WEEK_OF_YEAR
的 s (49/50) 中,即使两个日历的一周的第一天都等于 2。嗯.. 什么?
解决方案
我放弃了获取WEEK_OF_YEAR
并按照建议获取Date
本周的开始和结束。
// get rollback amt
temp.setTimeInMillis(set_time);
int rollback = 0;
int dayofweek = date.get(Calendar.DAY_OF_WEEK);
while(dayofweek != temp.getFirstDayOfWeek()) {
dayofweek--;
if(dayofweek == 0) dayofweek = 7;
rollback--;
}
int rollfwd = rollback + 6;
// get start bound
temp.setTimeInMillis(set_time);
temp.roll(Calendar.DAY_OF_YEAR, rollback);
temp.set(Calendar.HOUR_OF_DAY, 0);
temp.set(Calendar.MINUTE, 1);
Date start = temp.getTime();
// get end bound
temp.setTimeInMillis(set_time);
temp.roll(Calendar.DAY_OF_YEAR, rollfwd);
temp.set(Calendar.HOUR_OF_DAY, 23);
temp.set(Calendar.MINUTE, 59);
Date end = temp.getTime();
然后我可以检查Date
条目是否介于以下之间:
if(entrydate.after(start) && entrydate.before(end))