Get current week number from Date C#

 How can I get the current week number from the date using C# (dot net core)?


Imports:


using System;
using System.Collections.Generic;
using System.Linq;



Solution #1: Considering Sunday as the first day of the week.


public static int GetCurrentWeek(DateTime dt)
{
// Sunday as first day of week
  DateTime firstOfMonth = new DateTime(dt.Yeardt.Month1);
  return ((dt.Day - 1 + (int)firstOfMonth.DayOfWeek)) / 7 + 1;
}



Solution #2: Considering Monday as the first day of the week.


public static int GetCurrentWeek(DateTime dt)
{
  // Monday as first day of week
  DateTime firstOfMonth = new DateTime(dt.Year, dt.Month, 1);
  int dayOfWeek = (int)(firstOfMonth.DayOfWeek) - 1;
  if(dayOfWeek < 0) dayOfWeek = 6;
  return (dt.Day - 1 + dayOfWeek) / 7 + 1;
}


Method Usage:


Console.WriteLine (GetCurrentWeek(new DateTime(2022, 06,27)));


Comments

  1. What we have to consider monday as first day?. Do we have to +- 2 in that case.

    ReplyDelete

Post a Comment

Ask a Question

Name

Email *

Message *

Popular posts from this blog

All git commands you need — get rid of merge conflicts

Get the number of weeks in a month C#