Truncates to the minutes - CSharp System

CSharp examples for System:DateTime Minute

Description

Truncates to the minutes

Demo Code


using System.Globalization;
using System.Collections.Generic;
using System;/*from  w  w  w  .jav a2 s .com*/

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

            var part = dateTime.Minute / min;

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

Related Tutorials