Android 中 Calendar.setFirstDayOfWeek() 不起作用

在Android中,使用Calendar.setFirstDayOfWeek()设置起始周日时,需确保该操作在Calendar.setTimeInMillis()之前,否则设置无效。这是由于Android SDK的实现未调用computeFields()进行刷新,与JDK中的实现不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Calendar.setFirstDayOfWeek() 这个方法在调用的时候,应该在 Calendar.setTimeInMillis() 之前,否则不会生效,原因是 setFirstDayOfWeek() 这个方法在 Android SDK 中的实现只是做了参数的设置,并没有进行刷新(没有调用 computeFields() 方法),JDK 中的这个方法调用了刷新方法,下面是这一方法在 SDK 和 JDK 中的区别。


在 Android SDK 中的实现如下:

    /**
     * Sets the first day of the week for this {@code Calendar}.
     * The value should be a day of the week such as {@code MONDAY}.
     */
    public void setFirstDayOfWeek(int value) {
        firstDayOfWeek = value;
    }

在 JDK 中的实现如下:

    /**
     * Sets this Calendar's current time from the given long value.
     *
     * @param millis the new time in UTC milliseconds from the epoch.
     * @see #setTime(Date)
     * @see #getTimeInMillis()
     */
    public void setTimeInMillis(long millis) {
        // If we don't need to recalculate the calendar field values,
        // do nothing.
        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
            && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
            return;
        }
        time = millis;
        isTimeSet = true;
        areFieldsSet = false;
        computeFields();
        areAllFieldsSet = areFieldsSet = true;
    }

正确的使用方式:

    public static Integer parseWorkReportMonthly(long date) {
        Calendar calendar = getCalendar();
        //这里的设置有意义
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTimeInMillis(date);
        //这里设置没有意义
        // calendar.setFirstDayOfWeek(Calendar.SUNDAY);
        return calendar.get(Calendar.WEEK_OF_MONTH);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值