Last active
October 9, 2024 22:24
-
-
Save ridercz/ab35dd1d3fe7f74bdc72c88976e67aea to your computer and use it in GitHub Desktop.
TimeProvider for .NET supporting rounding time to last second or minute and time zone conversions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RoundedTimeProvider : TimeProvider { | |
// Private constructor to prevent direct instantiation | |
private RoundedTimeProvider() { } | |
// Factory methods for different precisions | |
public static RoundedTimeProvider NativePrecision(string? localTimeZoneName = null) => new() { | |
LocalTimeZoneInternal = localTimeZoneName == null ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(localTimeZoneName), | |
RoundingFunction = x => x, | |
}; | |
public static RoundedTimeProvider SecondPrecision(string? localTimeZoneName = null) => new() { | |
LocalTimeZoneInternal = localTimeZoneName == null ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(localTimeZoneName), | |
RoundingFunction = x => x.AddTicks(-x.Ticks % TimeSpan.TicksPerSecond), | |
}; | |
public static RoundedTimeProvider MinutePrecision(string? localTimeZoneName = null) => new() { | |
LocalTimeZoneInternal = localTimeZoneName == null ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(localTimeZoneName), | |
RoundingFunction = x => x.AddTicks(-x.Ticks % TimeSpan.TicksPerMinute), | |
}; | |
// Properties to hold the rounding function and the local time zone | |
private TimeZoneInfo LocalTimeZoneInternal { get; init; } = null!; | |
private Func<DateTimeOffset, DateTimeOffset> RoundingFunction { get; init; } = null!; | |
// Override the GetUtcNow method to apply the rounding function | |
public override DateTimeOffset GetUtcNow() => this.RoundingFunction(base.GetUtcNow()); | |
// Override the LocalTimeZone property to return the local time zone | |
public override TimeZoneInfo LocalTimeZone => this.LocalTimeZoneInternal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment