Salient Solutions

wrasslin ones and nones for fun and profit - Sky Sanders' Blog
posts - 96, comments - 70, trackbacks - 0

C# truncate DateTime

Here is an extension method that will let you truncate a DateTime to any resolution...

Usage:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

Class:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

 

 

Print | posted on Tuesday, April 20, 2010 9:44 PM | Filed Under [ CodeProject-Tip ]

Feedback

Gravatar

# love

new chanel handbag more prevalent in women because longines replica
10/22/2010 7:38 PM | coco chanel clothes

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 1 and 1 and type the answer here:

Powered by: