你的位置:首页 > ASP.net教程

[ASP.net教程].net 根据输入日期得到当前所在周的周一(可延伸获取周的任何一天)


  思想:主要根据DateTime类的DayOfWeek属性来得到周的英文名字,然后通过日期天数的加减运算得到周一。

1.调用:

   string today = "2015-7-13";//System.DateTime.Now.ToString();
   lblDay.Text = GetMondayOfTheWeek(today); 

2.方法:

private string GetMondayOfTheWeek(string today)
        {
            string sMonday = "";
            DateTime dateNow;
            try{
               dateNow= Convert.ToDateTime(today);
            }
            catch
            {
                sMonday="方法GetMondayOfWeeks传入的参数格式错误,请检查后重新调用!";
                return sMonday;
            }
            string dayOfWeekName = dateNow.DayOfWeek.ToString();
            int day=0;
            switch(dayOfWeekName)
            {
                 case "Monday":
                    day= 0;
                    break;
                case "Tuesday":
                     day= 1;
                    break;
                case "Wednesday":
                    day= 2;
                    break;
                case "Thursday":
                    day= 3;
                    break;
                case "Friday":
                    day= 4;
                    break;
                case "Saturday":
                     day= 5;
                    break;
                case "Sunday":
                     day=6;
                    break;
            }
            sMonday = dateNow.AddDays(-day).ToString("yyyy-M-d");  
           
            return sMonday;
        }