Truncates to the seconds - CSharp System

CSharp examples for System:DateTime Second

Description

Truncates to the seconds

Demo Code


using System.Globalization;
using System.Collections.Generic;
using System;//from   w w  w  .  java  2s  . c  om

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

            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second / sec * sec, dateTime.Kind);
        }
        /// <summary>
        /// Truncates <see cref="DateTime"/> to the seconds
        /// </summary>
        public static DateTime RoundToSecond(this DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind);
        }
}

Related Tutorials