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

CSharp examples for System:DateTime Week

Description

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

Demo Code


using System.Globalization;
using System;/*from  ww  w  .  j  a v a2 s  .co  m*/

public class Main{
        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);
        }
        /// <summary>
        /// Returns the FIRST possible time unit for provided DAY in dateTime
        /// (Same as DateTime.Date)
        /// </summary>
        public static DateTime StartOfDay(this DateTime dateTime)
        {
            return dateTime.Date;
        }
}

Related Tutorials