0

I have to calculate the week number based on a date. This might be easy and I've done in this way (thanks to another SO post):

public static int GetCurrentWeekNumber(DateTime time)
{
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

The new request is to calculate the week number not from Monday but from thursday to the next wednesday (included). Any hints?

Community
  • 1
  • 1
Ras
  • 628
  • 1
  • 11
  • 29

1 Answers1

2
CultureInfo.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Tuesday;

Edit: (thanks to comment)

https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.cultureinfo(v=vs.110).aspx

CultureInfo co = new new CultureInfo("en-US", true);
co.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Tuesday;
online Thomas
  • 8,864
  • 6
  • 44
  • 85
  • You will get an `InvalidOperationException` at runtime because the instance is readonly if you don't clone it. – Tim Schmelter Oct 15 '15 at 13:48
  • @TimSchmelter Point taken, so let's clone it :) – online Thomas Oct 15 '15 at 13:49
  • It does also not take this into account: _"calculate the week number from tuesday to the next wednesday (included)"_ Although that would be a 8 day week. I'm not sure if OP really wants it. – Tim Schmelter Oct 15 '15 at 13:53
  • Correct, it was a typo, I meant thursday – Ras Oct 15 '15 at 13:56
  • @TimSchmelter also something to consider, but there is no official way to give a weeknumber for a range exceeding the 7 days. As a week is always 7 days. But I'll give it a mathematical approach. (edit never mind after Ras's comment). For people who are curious: I wanted to write a modulo (%) 8 function that takes the first day of the year in consideration. – online Thomas Oct 15 '15 at 13:57
  • 2
    @user2754599: the method OP uses won't work immediately by changing the `DateTimeFormat.FirstDayOfWeek` to the desired day. Also, if you want to change the `FirstDayOfWeek` of the `InvariantCulture` this constructor doesn't help. You could use `Clone`: `var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); culture.DateTimeFormat.FirstDayOfWeek = weekStart;` – Tim Schmelter Oct 15 '15 at 14:04