C#时间函数扩展(计算第几周和周起止日期)


 

// 本周是本年第几周


private   int  DatePart(System.DateTime dt)
{
   
int weeknow = Convert.ToInt32(dt.DayOfWeek);//今天星期几
   int daydiff = (-1* (weeknow+1);//今日与上周末的天数差
   int days = System.DateTime.Now.AddDays(daydiff).DayOfYear;//上周末是本年第几天
   int weeks = days/7;
   
if(days%7 != 0)
{
    weeks
++;
   }

   
//此时,weeks为上周是本年的第几周
   return (weeks+1);
  }


 
// 本周起止日期

 
private   string  WeekRange(System.DateTime dt)
{
   
int weeknow = Convert.ToInt32(dt.DayOfWeek);
   
int daydiff = (-1* weeknow;
   
int dayadd = 6-weeknow;
   
string dateBegin = System.DateTime.Now.AddDays(daydiff).Date.ToString("MM月dd日");
   
string dateEnd = System.DateTime.Now.AddDays(dayadd).Date.ToString("MM月dd日");
   
return dateBegin + " - " +dateEnd;
  }



// 计算第几周(重新修改后)
public   int  GetWeekOfCurrDate(DateTime dt)
        
{
            
int Week = 1;
            
int nYear = dt.Year;
            System.DateTime FirstDayInYear 
= new DateTime(nYear, 11);
            System.DateTime LastDayInYear 
= new DateTime(nYear, 1231);
            
int DaysOfYear = Convert.ToInt32(LastDayInYear.DayOfYear);
            
int WeekNow = Convert.ToInt32(FirstDayInYear.DayOfWeek) - 1;
            
if (WeekNow < 0) WeekNow = 6;
            
int DayAdd = 6 - WeekNow;
            System.DateTime BeginDayOfWeek 
= new DateTime(nYear, 11);
            System.DateTime EndDayOfWeek 
= BeginDayOfWeek.AddDays(DayAdd);
            Week 
= 2;
            
for (int i = DayAdd + 1; i <= DaysOfYear; i++)
            
{
                BeginDayOfWeek 
= FirstDayInYear.AddDays(i);
                
if (i + 6 > DaysOfYear)
                
{
                    EndDayOfWeek 
= BeginDayOfWeek.AddDays(DaysOfYear - i - 1);
                }

                
else
                
{
                    EndDayOfWeek 
= BeginDayOfWeek.AddDays(6);
                }


                
if (dt.Month == EndDayOfWeek.Month && dt.Day <= EndDayOfWeek.Day)
                
{
                    
break;
                }

                Week
++;
                i 
= i + 6;
            }

            
return Week;
        }

你可能感兴趣的:(时间函数)