Decreases date precision down to week. Shifts date to monday - CSharp System

CSharp examples for System:DateTime Week

Description

Decreases date precision down to week. Shifts date to monday

Demo Code


using System.Globalization;
using System.Collections.Generic;
using System;/*from w ww. j a v a 2  s. c  o m*/

public class Main{
        /// <summary>
        /// Decreases date precision down to week. Shifts date to monday
        /// </summary>
        public static DateTime RoundToWeek(this DateTime dateTime)
        {
            var diff = dateTime.DayOfWeek - DayOfWeek.Monday;
            var dt = dateTime.AddDays(diff == -1 ? -6 : -diff); // shifting to monday

            return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, dateTime.Kind);
        }
}

Related Tutorials