首页 > 编程 > C# > 正文

C#中获得本周的周六和周日

2023-05-16 12:36:03
字体:
来源:转载
供稿:网友

本文给出一个方法(函数)用来获得当前星期的周六和周日,这在我们日常编程中经常能使用到。

方法的名字为:ConvertDateToWeek

#region ConvertDateToWeek

public static void ConvertDateToWeek(DateTime date,out DateTime firstdate,out DateTime lastdate)
        {   
            DateTime first=System.DateTime.Now;
            DateTime last=System.DateTime.Now;
            switch (date.DayOfWeek)
            {               
                case System.DayOfWeek.Monday:
                    first=date.AddDays(-1);
                    last=date.AddDays(5);
                    break;
                case System.DayOfWeek.Tuesday:
                    first=date.AddDays(-2);
                    last=date.AddDays(4);
                    break;
                case System.DayOfWeek.Wednesday:
                    first=date.AddDays(-3);
                    last=date.AddDays(3);
                    break;
                case System.DayOfWeek.Thursday:
                    first=date.AddDays(-4);
                    last=date.AddDays(2);
                    break;
                case System.DayOfWeek.Friday:
                    first=date.AddDays(-5);
                    last=date.AddDays(1);
                    break;
                case System.DayOfWeek.Saturday:
                    first=date.AddDays(-6);
                    last=date;
                    break;
                case System.DayOfWeek.Sunday:
                    first=date;
                    last=date.AddDays(6);
                    break;               
            }
            firstdate=first;
            lastdate=last;
        }
        #endregion   

具体使用方法如下:

DateTime firstdate=System.DateTime.Now;   

DateTime lastdate=System.DateTime.Now;

ConvertDateToWeek(date,out firstdate,out lastdate);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表