C#的一些获取时间的例子
C#的一些获取时间的例子
从周一到周日的顺序,获取排序数值:
int i = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;
获取某日起,星期一日期:
public static DateTime GetMondayDate(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Subtract(ts);
}
获取当前时间上周六的时间:
public DateTime GetLastSaturday()
{
DateTime time = DateTime.Now;
if (time.DayOfWeek == DayOfWeek.Sunday)
{
time = time.AddDays(-2);
}
else
time = time.AddDays(-1);
while (time.DayOfWeek != DayOfWeek.Saturday)
{
time = time.AddDays(-1);
}
return time;
}