private int week(DateTime day)
{
string y = day.Year.ToString();
string m = day.Month.ToString();
string s = y + "-" + m + "-1";
DateTime dt = DateTime.Parse(s);
int d = day.Day - dt.Day;
int w = 1;
for (int i = 1; i <= d; i++)
{
DateTime dt1= dt.AddDays(i);
if (dt1.DayOfWeek == DayOfWeek.Sunday)
{
w = w + 1;
}
}
return w;
}
上面的测试正确。
int currentWeek = 0;
//构造当前月的1号
DateTime dd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
//获得当前月1号是一个星期的第几天
int week = (int)dd.DayOfWeek;
//用来存储,当第一天不是星期天时,这个星期还有多少天
int t1 = 0;
if (week > 0)
{
//如果不是一个星期日
currentWeek++;
t1 = 7 - week;
}
int t2 = (DateTime.Now.Day - t1) % 7;
int t3 = 0;
if (t2 != 0)
{
t3 = (DateTime.Now.Day - t1) / 7 + 1;
}
else
{
t3 = (DateTime.Now.Day - t1) / 7;
}
currentWeek += t3;
这个是网上找到的,应该也可以。
下面的是计算一年的第几周
#region 得到当前日期是该年度的第几周,此处需要注意的是:不能从该年的1-1算起,判断该年的1-1是星期几,如果是周一,那么从1-1算起,如果非周一,要将偏移量减去
/// <summary >
/// 能够得到该年有多少周,传递参数的时候“当前年+12-31”
/// </summary >
/// <param name="dt" > </param >
/// <returns > </returns >
public string GetWeek(DateTime dt)
{
string returnStr="";
System.DateTime fDt=DateTime.Parse(dt.Year.ToString()+"-01-01");
int k=Convert.ToInt32(fDt.DayOfWeek);//得到该年的第一天是周几
if(k==0)
{
k=7;
}
int l=Convert.ToInt32(dt.DayOfYear);//得到当天是该年的第几天
l=l-(7-k+1);
if(l <=0)
{
returnStr="1";
}
else
{
if (l % 7 == 0)
{
returnStr=(l/7+1).ToString();
}
else
{
returnStr=(l/7 +2).ToString();//不能整除的时候要加上前面的一周和后面的一周
}
}
return returnStr;
}
#endregion
以下是另一种方法
//当天与该周星期一相差的天数
private int getModdayNum(System.DayOfWeek dw)
...{
int weeknow = Convert.ToInt32(dw);
int moddayNum = (-1) * weeknow+1;
return moddayNum;
}
//当天与该周星期日相差的天数
private int getSundayNum(System.DayOfWeek dw)
...{
int weeknow = Convert.ToInt32(dw);
int sundayNum = 7-weeknow;
return sundayNum;
}
//该周星期一的日期
private string getWeekMonday(System.DayOfWeek dw,string timeFormateStr)
...{
int weeknow = Convert.ToInt32(dw);
int moddayNum = (-1) * weeknow+1;
string weekMonday = System.DateTime.Now.AddDays(moddayNum).Date.ToString(timeFormateStr);
return weekMonday;
}
//该周星期日的日期
private string getWeekSunday(System.DayOfWeek dw,string timeFormateStr)
...{
int weeknow = Convert.ToInt32(dw);
int sundayNum = 7-weeknow;
string weekSunday = System.DateTime.Now.AddDays(sundayNum).Date.ToString(timeFormateStr);
return weekSunday;
}
//本周是本年第几周
private int weekNum(System.DayOfWeek dw)
...{
int weeknow = Convert.ToInt32(dw);//今天星期几
int daydiff = (-1) * (weeknow+1);//今日与上周末的天数差
int days = System.DateTime.Now.AddDays(daydiff).DayOfYear;//上周末是本年第几天
int weeks = days/7;
if(days%7 != 0)
...{
weeks++;
}
return (weeks+2);
}
//调用方法
string datetime = getWeekMonday(System.DateTime.Now.DayOfWeek,"yyyy-MM-dd");