如何正确手动配置NodaTime IWeekYearRule?

时间:2019-01-14 07:51:32

标签: c# nodatime

我将NodaTime包装在我们的软件中使用,为了适应未来发展,我认为我会根据Bcl DateTimeFormat设置IWeekYearRule,如下所示:

var culture = CultureInfo.CurrentCulture;
var weekRule = WeekYearRules.FromCalendarWeekRule(
    culture.DateTimeFormat.CalendarWeekRule,
    culture.DateTimeFormat.FirstDayOfWeek);

在挪威,我们正在进行以下设置:

CalendarWeekRule.FirstFourDayWeek
DayOfWeek.Monday

但是,令我惊讶的是,当我检查以下两个日期的星期数时,kalender.no表示不同意:

2018-12-31: week 53 of 2018 (kalender.no says week 1 [implied: of 2019])
2019-01-01: week 1 of 2019  (kalender.no agrees here)

但是,如果我使用WeekYearRules.Iso,它们都会返回“ 2019年的第1周”。

我有很多问题,但让我们关注最直接的问题:

我该如何编写代码来“保护未来”该库的这一部分,这样,当我们开始将软件推广到世界的更多地区时,它将根据开箱即用的方式正确计算周数。当地文化?

这是不可能的,因为文化信息不包含此信息吗?

下面是一个LINQPad示例,演示了NodaTime行为(很抱歉,不包括[mcve]开头):

void Main()
{
    "-------------- ISO --------------".Dump();
    Test(WeekYearRules.Iso);

    "-------------- BCL --------------".Dump();
    Test(WeekYearRules.FromCalendarWeekRule(CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));
}

public static void Test(IWeekYearRule rule)
{
    var date = new LocalDate(2018, 12, 31);
    $"{date}, {rule.GetWeekOfWeekYear(date)} in {rule.GetWeekYear(date)}".Dump();

    date = new LocalDate(2019, 1, 1);
    $"{date}, {rule.GetWeekOfWeekYear(date)} in {rule.GetWeekYear(date)}".Dump();
}

输出:

-------------- ISO --------------
mandag 31. desember 2018, 1 in 2019
tirsdag 1. januar 2019, 1 in 2019
-------------- BCL --------------
mandag 31. desember 2018, 53 in 2018
tirsdag 1. januar 2019, 1 in 2019

(请注意,ISO输出是挪威的正确输出)

这是NodaTime 2.4.4,Windows 10,.NET 4.7.2。


这是不使用NodaTime的LINQPad示例:

void Main()
{
    var culture = CultureInfo.GetCultureInfo("nb-NO");

    var calendarWeekRule = culture.DateTimeFormat.CalendarWeekRule.Dump();
    var firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek.Dump();

    var date = new DateTime(2018, 12, 31);
    $"{date.DayOfWeek} {date}, week {culture.Calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek)}".Dump();

    date = new DateTime(2019, 1, 1);
    $"{date.DayOfWeek} {date}, week {culture.Calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek)}".Dump();
}

输出:

FirstFourDayWeek
Monday
Monday 31.12.2018 00.00.00, week 53
Tuesday 01.01.2019 00.00.00, week 1

星期一是与2019年第1周相同的一周,在挪威这里算作2019年第1周,因此这两个日期中的第一个应该确实是:

Monday 31.12.2018 00.00.00, week 1

0 个答案:

没有答案