1. 程式人生 > >C#中周,月,第幾周,周開始結束時間de方法總結

C#中周,月,第幾周,周開始結束時間de方法總結

get months 開始時間 fwe cal 得到 pic html csharp

1、c#獲取當前時間是本年的第幾周,本月的第幾周

    private  static int getWeekNumInMonth(DateTime daytime)  
            {  
                int dayInMonth = daytime.Day;  
                //本月第一天  
                DateTime firstDay = daytime.AddDays(1 - daytime.Day);  
                //本月第一天是周幾  
                int weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;  
                //本月第一周有幾天  
                int firstWeekEndDay = 7 - (weekday - 1);  
                //當前日期和第一周之差  
                int diffday = dayInMonth - firstWeekEndDay;  
                diffday = diffday > 0 ? diffday : 1;  
                //當前是第幾周,如果整除7就減一天  
                int WeekNumInMonth = ((diffday % 7) == 0  
                 ? (diffday / 7 - 1)  
                 : (diffday / 7)) + 1 + (dayInMonth > firstWeekEndDay ? 1 : 0);  
                return WeekNumInMonth;  
            }  

2、獲取本年的第幾周:

    GregorianCalendar gc = new GregorianCalendar();  
               int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);  
               Console.WriteLine(weekOfYear);  
               Console.ReadLine();  

3、c#得到本月有幾周和這幾周的起止時間示例代碼

 /// <summary>
             /// 獲得本月有幾周
             /// </summary>
             /// <param name="a"></param>
             /// <returns></returns>
             public  void NumWeeks(DateTime dt)
             {
                 //年
                 int year = dt.Year;
                 //月
                 int month = dt.Month;
                 //當前月第一天
                 DateTime weekStart = new DateTime(year, month, 1);
                 //該月的最後一天
                 DateTime monEnd = weekStart.AddMonths(1).AddDays(-1);
                 int i = 1;
                 //當前月第一天是星期幾
                 int dayOfWeek = Convert.ToInt32(weekStart.DayOfWeek.ToString("d"));
                 //該月第一周結束日期
                 DateTime weekEnd = dayOfWeek == 0 ? weekStart : weekStart.AddDays(7 - dayOfWeek);

                 richTextBox2.Text += "第" + i + "周起始日期: " + weekStart.ToShortDateString() + "   結束日期: " + weekEnd.ToShortDateString() + "\n";

                 //當日期小於或等於該月的最後一天
                 while (weekEnd.AddDays(1) <= monEnd)
                 {
                     i++;
                     //該周的開始時間
                     weekStart = weekEnd.AddDays(1);
                     //該周結束時間
                     weekEnd = weekEnd.AddDays(7) > monEnd ? monEnd : weekEnd.AddDays(7);

                     richTextBox2.Text += "第" + i + "周起始日期: " + weekStart.ToShortDateString() + "   結束日期: " + weekEnd.ToShortDateString() + "\n";
                 }

                 richTextBox2.Text += year + "年" + month + "月共有" + i + "周\n";
             }

4、My97DatePicker日期插件的常用功能說明

http://jingyan.baidu.com/article/e6c8503c7244bae54f1a18c7.html

以上方法均為實際使用,親測!!!

總結推薦下

各方法出處省略。

C#中周,月,第幾周,周開始結束時間de方法總結