如何确定一周是奇数还是偶数

时间:2015-06-10 04:59:56

标签: android

我想确定今天的人是偶数还是奇数!

我写了这段代码,但那不起作用。

public static int getWeekType(Date termStartDate, Date dateToday){
    Calendar today = Calendar.getInstance();
    today.setTime(dateToday);

    Calendar thatDay = Calendar.getInstance();
    thatDay.setTime(termStartDate);

    long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
    long days = diff / (24 * 60 * 60 * 1000);

    int dayOfWeek = (today.getTime().getDay() + 1) % 7;
    int weekNum = (int) ((days + dayOfWeek) / 7);
    return (weekNum + 1) % 2; // 0(even) or 1(odd)
}

我怎么做?

修改

结果样本:

06-10 04:53:16.690    I/week-type﹕ ---- week type: 1 - Thu Jun 18 04:52:21 GMT 2015
06-10 04:53:17.858    I/week-type﹕ ---- week type: 1 - Fri Jun 19 04:52:21 GMT 2015
06-10 04:53:18.674    I/week-type﹕ ---- week type: 0 - Sat Jun 20 04:52:21 GMT 2015
06-10 04:53:19.474    I/week-type﹕ ---- week type: 1 - Sun Jun 21 04:52:21 GMT 2015
06-10 04:53:20.622    I/week-type﹕ ---- week type: 1 - Mon Jun 22 04:52:21 GMT 2015
06-10 04:53:21.390    I/week-type﹕ ---- week type: 1 - Tue Jun 23 04:52:21 GMT 2015
06-10 04:53:22.890    I/week-type﹕ ---- week type: 0 - Wed Jun 24 04:52:21 GMT 2015

1 个答案:

答案 0 :(得分:1)

您可以直接根据两个日期之间的差异以毫秒计算weekNum

这应该有效:

public static int getWeekType(Date termStartDate, Date dateToday){
    Calendar today = Calendar.getInstance();
    today.setTime(dateToday);

    Calendar thatDay = Calendar.getInstance();
    thatDay.setTime(termStartDate);

    long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
    long weekNum = diff / (7 * 24 * 60 * 60 * 1000);

    return (weekNum + 1) % 2; // 0(even) or 1(odd)
}

如果您想从包含termStartDate的一周开始计算,请修改它以添加thatDate而不是today的星期几:

public static int getWeekType(Date termStartDate, Date dateToday){
    Calendar today = Calendar.getInstance();
    today.setTime(dateToday);

    Calendar thatDay = Calendar.getInstance();
    thatDay.setTime(termStartDate);

    long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
    long days = diff / (24 * 60 * 60 * 1000);

    int dayOfWeek = thatDay.get(Calendar.DAY_OF_WEEK) - 1;
    int weekNum = (int) ((days + dayOfWeek) / 7);
    return (weekNum + 1) % 2; // 0(even) or 1(odd)
}

注意:不推荐使用getDay(),因此我将其更改为使用Calendar.get(Calendar.DAY_OF_WEEK)