To Week Start - CSharp System

CSharp examples for System:DateTime Week

Description

To Week Start

Demo Code


using System;//w  w w .ja v a  2 s .  c  om

public class Main{
        private static DateTime ToWeekStart(this DateTime date, DayOfWeek week)
        {
            DateTime WeekStart = new DateTime();
            switch (week)
            {
                case DayOfWeek.Monday:
                    WeekStart = date;
                    break;
                case DayOfWeek.Tuesday:
                    WeekStart = date.AddDays(-1);
                    break;
                case DayOfWeek.Wednesday:
                    WeekStart = date.AddDays(-2);
                    break;
                case DayOfWeek.Thursday:
                    WeekStart = date.AddDays(-3);
                    break;
                case DayOfWeek.Friday:
                    WeekStart = date.AddDays(-4);
                    break;
                case DayOfWeek.Saturday:
                    WeekStart = date.AddDays(-5);
                    break;
                case DayOfWeek.Sunday:
                    WeekStart = date.AddDays(-6);
                    break;
            }
            return WeekStart;
        }
        public static DateTime ToWeekStart(this DateTime value)
        {
            DateTime weekStart = ToWeekStart(value, value.Date.DayOfWeek);
            string shortDate = weekStart.ToShortDateString();
            return Convert.ToDateTime(shortDate);
        }
        public static DateTime ToWeekStart(this string value)
        {
            DateTime date = Convert.ToDateTime(value);
            DateTime weekStart = ToWeekStart(date, date.Date.DayOfWeek);
            string shortDate = weekStart.ToShortDateString();
            return Convert.ToDateTime(shortDate);
        }
}

Related Tutorials