AddSeconds for TimeOnly

One really annoying fact of life you get when dealing with TimeOnly is that class has no AddSeconds method (AddMilliseconds or AddTicks either). But adding that missing functionality is not that hard – enter extension method.

While TimeOnly has no direct methods to add anything below a minute resolution, it does allow for creating a new instance using 100 ns ticks. So we might as well use it.

Extension methods
public static class TimeOnlyExtensions
{
public static TimeOnly AddSeconds(this TimeOnly time, double seconds)
{
var ticks = (long)(seconds * 10000000 + (seconds >= 0 ? 0.5 : -0.5));
return AddTicks(time, ticks);
}

public static TimeOnly AddMilliseconds(this TimeOnly time, int milliseconds)
{
var ticks = (long)(milliseconds * 10000 + (milliseconds >= 0 ? 0.5 : -0.5));
return AddTicks(time, ticks);
}

public static TimeOnly AddTicks(this TimeOnly time, long ticks)
{
return new TimeOnly(time.Ticks + ticks);
}
}

With one simple using static TimeOnlyExtensions; we get to correct this oversight. Hopefully this won’t be needed in the future. While easy enough, it’s annoying that such obvious methods are missing.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.