ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Round to Nearest TimeSpan

Rounds a TimeSpan value to the nearest timespan given

Source

public static TimeSpan RoundToNearest(this TimeSpan a, TimeSpan roundTo){
		long ticks = (long)(Math.Round(a.Ticks / (double)roundTo.Ticks) * roundTo.Ticks);
		return new TimeSpan(ticks);
	}

Example

TimeSpan example = DateTime.Now.TimeOfDay;
Console.WriteLine(example.RoundToNearest(TimeSpan.FromMinutes(15)));

Author: slowpython

Submitted on: 28 feb. 2014

Language: C#

Type: TimeSpan

Views: 9836