Round the datetime to nearest timespan. - CSharp System

CSharp examples for System:TimeSpan

Description

Round the datetime to nearest timespan.

Demo Code


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

public class Main{
        /// <summary>
        /// Round the datetime to nearest timespan. 
        /// The following code is from SO: http://stackoverflow.com/q/1393696/809357
        /// </summary>
        /// <param name="date"></param>
        /// <param name="span"></param>
        /// <returns></returns>
        public static DateTime Round(this DateTime date, TimeSpan span)
        {
            long ticks = (date.Ticks + (span.Ticks / 2) + 1) / span.Ticks;
            return new DateTime(ticks * span.Ticks);
        }
}

Related Tutorials