Get week of month C# [duplicate]

空扰寡人 提交于 2019-12-04 14:13:35

Here is the method:

static int GetWeekNumberOfMonth(DateTime date)
{
    date = date.Date;
    DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
    DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    if (firstMonthMonday > date)
    {
        firstMonthDay = firstMonthDay.AddMonths(-1);
        firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    }
    return (date - firstMonthMonday).Days / 7 + 1;
}

Test:

Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 6)));  // 1
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 30))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 1)));  // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 3)));  // 1
  public static int GetWeekNumber(DateTime dt)
  {
          CultureInfo curr= CultureInfo.CurrentCulture;
          int week = curr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return week;
  }

The method will return a structure with the first and last date of that quarter.

 private String test()
    {
        DateRangeStruct retVal;
        retVal.startDate = retVal.endDate = Now;
        retVal = DateRange(DateRangeOptions.Week, DateTime.Today);
    }

please refer these link http://nonsequiturs.com/articles/find-the-first-and-last-day-of-a-date-range-using-c-and-asp-net/

I think this is what you want:

public static int GetWeekOfMonth(DateTime date)  
{  
    DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);  

    while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)  
        date = date.AddDays(1);  

    return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays  / 7f) + 1;  
} 

Its authored by David M Morton on http://social.msdn.microsoft.com/Forums/vstudio/en-US/bf504bba-85cb-492d-a8f7-4ccabdf882cb/get-week-number-for-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!