Returns the LAST possible time unit for provided WEEK in dateTime Based on CURRENT THREAD CULTURE - CSharp System

CSharp examples for System:DateTime Week

Description

Returns the LAST possible time unit for provided WEEK in dateTime Based on CURRENT THREAD CULTURE

Demo Code


using System.Globalization;
using System;//from   ww  w .  ja v a  2  s.  com

public class Main{
        /// <summary>
        /// Returns the LAST possible time unit for provided WEEK in dateTime Based on CURRENT THREAD CULTURE
        /// </summary>
        public static DateTime EndOfWeek(this DateTime dateTime)
        {
            return dateTime.StartOfWeek().AddDays(7).AddTicks(-1);
        }
        private static DateTime StartOfWeek(this DateTime dateTime, DayOfWeek startOfWeek)
        {
            int diff = dateTime.DayOfWeek - startOfWeek;
            if (diff < 0)
            {
                diff += 7;
            }

            DateTime mondayStart = dateTime.AddDays(-1 * diff).StartOfDay();

            return mondayStart;
        }
        /// <summary>
        /// Returns the FIRST possible time unit for provided WEEK in dateTime Based on CURRENT THREAD CULTURE
        /// </summary>
        public static DateTime StartOfWeek(this DateTime dateTime)
        {
            var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

            return StartOfWeek(dateTime, firstDayOfWeek);
        }
}

Related Tutorials