C# 得到C月的一周#

C# 得到C月的一周#,c#,winforms,datetime,week-number,C#,Winforms,Datetime,Week Number,我想用c#桌面应用程序查找一个日期在第几周 我一直在寻找谷歌,但没有一个适合我的需要 我如何在一个月内得到一周,如下例所示 例如: 我想要2014年1月6日=1月的第一周 2014年1月30日=1月的第四周 但2014年2月1日=1月第4周 2014年2月3日是2月的第一周,该方法将返回该季度第一个和最后一个日期的结构 public static int GetWeekNumber(DateTime dt) { CultureInfo curr= CultureInf

我想用c#桌面应用程序查找一个日期在第几周

我一直在寻找谷歌,但没有一个适合我的需要

我如何在一个月内得到一周,如下例所示

例如:

我想要2014年1月6日=1月的第一周

2014年1月30日=1月的第四周

但2014年2月1日=1月第4周


2014年2月3日是2月的第一周,该方法将返回该季度第一个和最后一个日期的结构

  public static int GetWeekNumber(DateTime dt)
  {
          CultureInfo curr= CultureInfo.CurrentCulture;
          int week = curr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return week;
  }
 private String test()
    {
        DateRangeStruct retVal;
        retVal.startDate = retVal.endDate = Now;
        retVal = DateRange(DateRangeOptions.Week, DateTime.Today);
    }
请参考这些链接 以下是方法:

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;
}
测试:


我想这就是你想要的:

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;  
} 

它的作者是大卫·M·莫顿

一周的第一天是什么?那么2014年1月1日的周数是多少?那么你的定义是“第一周是从该月的第一个星期一到下一个星期天”?你可以得到的第一个谷歌结果是:如果你可以回避,就这么做。他想要的是月的周数,而不是年的周数。这段代码很有趣,但它将返回年的周数,而不是月数。另外,要注意“FirstFourDayWeek”,它可能会给出无人参与的结果。如果我使用datetime,结果是16。现在,我希望像我的示例一样获得每月一周的结果。我想要2014年1月6日=1月的第一周。2014年1月30日=1月的第四周。但2014年2月1日=1月第4周。2014年2月3日是2月的第一周。@Enkhay Yea,你的问题搞错了,可能是你可以添加一些代码来返回当月的一周,可能会获得否决票Dim WeekNumber作为整数=GetWeekNumber(MyDate)-GetWeekNumber(LastDayLastMonth)此代码计算周数,而不考虑第一周的日期是否在周一。我想要的是每个月的第一个星期一是这个月的第一个星期。例如,如果1月1日,而不是周一,意味着1月1日,包括上个月的最后一周。绝对值,这就是我想要的代码。非常感谢@Ulugbek这在2021年3月21日不起作用
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;  
}