C# 星期相关代码实例

本文为引用文章 仅作整理自用 原文链接: https://www.cnblogs.com/yxyl/p/9992841.html @网吧看压力大

从周一到周日的顺序,获取排序数值:

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

 

posted @ 2018-11-21 17:29  Alpha燕  阅读(244)  评论(0编辑  收藏  举报