Java 返回的Android日历日(周中日)';1';星期一。。。但只有一次?
我有一个应用程序,使用警报来启动无线电流。它具有“每日重复”功能。为了检查警报是否会在某一天触发,我检查了“day_OF_WEEK”是否在数组中。大概是这样的:Java 返回的Android日历日(周中日)';1';星期一。。。但只有一次?,java,android,calendar,Java,Android,Calendar,我有一个应用程序,使用警报来启动无线电流。它具有“每日重复”功能。为了检查警报是否会在某一天触发,我检查了“day_OF_WEEK”是否在数组中。大概是这样的: int[] repeatOnDays = [0,1,1,1,1,1,1]; // first nr is sunday, last is saturday int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1; // -1 because Sunday==1 but its index
int[] repeatOnDays = [0,1,1,1,1,1,1]; // first nr is sunday, last is saturday
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1; // -1 because Sunday==1 but its index in the array is 0
if (repeatOnDays[dayOfWeek]>0) { /* FIRE ALARM TODAY */ }
else { /* DON'T FIRE ALARM TODAY */ }
(注意:上面的代码可能不是100%java,我已经简化了内容)
今天早上,当我的代码运行时,它说dayOfWeek是“0”(星期日),但现在是星期一!当我设置另一个闹钟时,它突然说星期一是“1”
什么?这怎么会发生
//更新:以下是实际代码:
JSONArray repeatDaily = new JSONArray("[0,1,1,1,1,1,1]"); // <- This is not actually here but it may help read the rest of the code :)
boolean fireToday = true;
if (repeat.equals("daily")) {
Log.d(APPTAG," > Daily repeat..");
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
if (repeatDaily.length()<dayOfWeek) { fireToday = false; }
else if (repeatDaily.getInt(dayOfWeek)>0) { fireToday = true; }
else { fireToday = false; }
Log.d(APPTAG," > Day: "+ dayOfWeek +", "+ repeatDaily.getInt(dayOfWeek));
}
if (!fireToday) {
Log.d(APPTAG," > Do not need to fire today");
return; // <-- important stuff
}
看来是我自己的错。在粘贴代码之前的几行,我设置了日历的时间:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMs);
但我有一些奇怪的代码,在某些情况下,会导致timeInMs成为过去的日期
改成
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
这应该可以解决问题:p注意
一周中的第几天
并非所有国家都需要相同。如果您只需要二进制值,请使用布尔[]而不是int[]。您的日历是如何设置的,周日计算的UTC时间是多少?@laalto UTC是今天早上5:30(1月19日星期一)。星期天是一周中的第一天,星期一是第二天。这就是为什么我有“-1”,所以星期天是0,星期一是1,等等。为日历设置区域设置
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());