指定された日付の正しい週番号を取得する 質問する

指定された日付の正しい週番号を取得する 質問する

私はグーグルでいろいろ検索してたくさんの解決策を見つけましたが、どれも2012-12-31の正しい週番号を教えてくれませんでした。MSDNの例(リンク) は失敗します。

2012-12-31 は月曜日なので、第 1 週になるはずですが、試したすべての方法で 53 になります。試した方法のいくつかを以下に示します。

MDSN ライブラリより:

DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);

解決策2:

return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

解決策3:

CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;

アップデート

次のメソッドは、日付が 2012-12-31 の場合、実際には 1 を返します。つまり、私の問題は、メソッドが ISO-8601 標準に従っていなかったことです。

// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
    // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll 
    // be the same week# as whatever Thursday, Friday or Saturday are,
    // and we always get those right
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

ベストアンサー1

このMSDNページISO8601 の週番号と .Net の週番号には若干の違いがあります。

より詳しい説明については、MSDN ブログのこの記事を参照してください: "Microsoft .Net における ISO 8601 週番号形式

簡単に言うと、.Net では週を複数の年に分割できますが、ISO 標準では分割できません。この記事には、年の最後の週の正しい ISO 8601 週番号を取得する簡単な関数も記載されています。

更新次のメソッドは実際には 1 を返しますが、2012-12-31これは ISO 8601 では正しい値です (例: ドイツ)。

// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
    // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll 
    // be the same week# as whatever Thursday, Friday or Saturday are,
    // and we always get those right
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
} 

おすすめ記事