Truncates to the hours - CSharp System

CSharp examples for System:DateTime Hour

Description

Truncates to the hours

Demo Code


using System.Globalization;
using System.Collections.Generic;
using System;//from   w  w  w. j  ava2 s .  c o m

public class Main{
        /// <summary>
        /// Truncates <see cref="DateTime"/> to the <paramref name="hour"/> hours
        /// </summary>
        /// <param name="dateTime"><see cref="DateTime"/> to truncate</param>
        /// <param name="hour">5 - truncates to 5 hours</param>
        public static DateTime RoundToHour(this DateTime dateTime, int hour)
        {
            if (hour < 1 || hour > 23)
            {
                throw new ArgumentOutOfRangeException(nameof(hour), hour, "Should be number in range 1..23");
            }

            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour / hour * hour, 0, 0, dateTime.Kind);
        }
        /// <summary>
        /// Truncates <see cref="DateTime"/> to the hours
        /// </summary>
        /// <param name="dateTime"><see cref="DateTime"/> to truncate</param>
        public static DateTime RoundToHour(this DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, dateTime.Kind);
        }
}

Related Tutorials