gpt4 book ai didi

android - GregorianCalendar setFirstDayOfWeek 不影响牛轧糖前的 WEEK_OF_YEAR

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:49:02 26 4
gpt4 key购买 nike

下面的代码在 Nougat 和 pre-Nougat 上给出了不同的结果。看一看,如果你愿意,可以自己尝试一下。如果有人能向我解释原因并提供解决方案,我将不胜感激。

我想要正确的 WEEK_OF_YEAR 值,取决于一周的第一天,适用于所有 Android 版本。我有一个时间表应用程序,我经常使用 gregorianCalendar,所以我不想切换到另一个类/库。

    //default first day of the week is Monday for replication. I live in the Netherlands, it's weird.
Locale l = new Locale("nl", "NL");

GregorianCalendar test = new GregorianCalendar(l);
test.set(Calendar.YEAR, 2017);
test.set(Calendar.MONTH, 0);
test.set(Calendar.DAY_OF_MONTH, 29);//this is a Sunday

int week = test.get(Calendar.WEEK_OF_YEAR);//should be 4
test.setFirstDayOfWeek(1);//Set it to Sunday
int week2 = test.get(Calendar.WEEK_OF_YEAR);//should be 5 but is 4 below nougat???

最佳答案

如果您查看 release notes for Nougat您可以看到对 Locales 的支持得到了增强。

特别是,

Prior to Android 7.0, Android could not always successfully match app and system locales.

我也在自己的设备上注意到了这一点。我的手机设置为英语(澳大利亚)语言环境。在牛轧糖之前,

DateTimeFormat.forPattern("dd MMMM").print(new LocalDate(2017,1,29));

会打印 29 Jan(没有句号/句点),但在 Nougat 之后它会打印 29 Jan.(有句点)。

虽然我很难给出确切的细节,但您的情况似乎就是这样。后牛轧糖,手机能够更好地匹配应用程序和系统区域设置,包括您的区域设置的一周的第一天。在任何情况下,通过调试器逐步查找根本原因是行不通的,因为调用是在 libcore 内部处理的,而不是在源代码中公开的 Java 类。

如果 Android 设备错误地报告了一年的第一天/一年的第一周,除了解决它之外您几乎无能为力:

if (android.os.Build.VERSION.SDK_INT < 24) {
//pre-Nougat logic
}
else {
//Nougat/post-Nougat logic
}

您也可以尝试使用 enhanced replacement for GregorianCalendar (在 SDK 24 中添加)来解决您的问题。

如果你使用类似 Joda-time 的类或使用新的 JSR-310类(通过 ThreeTen 向后移植),您可能无需绕过 GregorianCalendar 即可获得所需内容。一般来说,这些类更容易使用并且更不容易出错。由于这样的问题,许多开发人员已经放弃了 java.util.Calendarjava.util.Date。请看答案to this canonical question详情

如果您要使用 Joda,则可以使用 LocalDate.fromCalendarFields(test) 将您的 GregorianCalendar 对象转换为 LocalDate。这些类(class)使用 ISO 标准,其中一周的第一天始终是星期一。然后,您将在它们之上编写您想要的逻辑。然后 GregorianCalendar 的问题将被“隔离”为一个简单的问题,即检索给定区域设置的一年中的第一周。如果您的应用包含对服务器的调用,您可以改为通过 API 调用为一周的第一天提供服务。

更新:

注意时区行为已在 Android O 中更新:

其他语言环境和国际化相关的更改如下:

Time zone name parsing has changed. Previously, Android devices used the system clock value sampled at boot time to cache the time zone names used for parsing date times. As a result, parsing could be negatively affected if the system clock was wrong at boot time or in other, rarer cases. Now, in common cases the parsing logic uses ICU and the current system clock value when parsing time zone names. This change provides more correct results, which may differ from earlier Android versions when your app uses classes like SimpleDateFormat. Android O updates the version of ICU to version 58.

关于android - GregorianCalendar setFirstDayOfWeek 不影响牛轧糖前的 WEEK_OF_YEAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com