Last active
September 2, 2016 01:44
-
-
Save jsmarble/65befee9563859642d1278aaba742238 to your computer and use it in GitHub Desktop.
This file contains 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 TimeSpanInterval | |
{ | |
private readonly Func<TimeSpan, double> fromTimeSpan; | |
private readonly Func<double, TimeSpan> toTimeSpan; | |
private TimeSpanInterval(string name, Func<double, TimeSpan> toTimeSpan, Func<TimeSpan, double> fromTimeSpan) | |
{ | |
this.Name = name; | |
this.toTimeSpan = toTimeSpan; | |
this.fromTimeSpan = fromTimeSpan; | |
} | |
public string Name { get; private set; } | |
public TimeSpan ToTimeSpan(double value) | |
{ | |
return toTimeSpan(value); | |
} | |
public double GetValueFromTimeSpan(TimeSpan value) | |
{ | |
return fromTimeSpan(value); | |
} | |
public static TimeSpanInterval InferFromTimeSpan(TimeSpan timeSpan) | |
{ | |
if (IsWholeInteger(timeSpan.TotalDays)) | |
return TimeSpanInterval.Days; | |
else if (IsWholeInteger(timeSpan.TotalHours)) | |
return TimeSpanInterval.Hours; | |
else if (IsWholeInteger(timeSpan.TotalMinutes)) | |
return TimeSpanInterval.Minutes; | |
else if (IsWholeInteger(timeSpan.TotalSeconds)) | |
return TimeSpanInterval.Seconds; | |
else if (IsWholeInteger(timeSpan.TotalMilliseconds)) | |
return TimeSpanInterval.Milliseconds; | |
else | |
return TimeSpanInterval.Ticks; | |
} | |
private static bool IsWholeInteger(double value) | |
{ | |
return value % 1 == 0; | |
} | |
public static readonly TimeSpanInterval Ticks = new TimeSpanInterval("Ticks", db => TimeSpan.FromTicks(Convert.ToInt64(db)), ts => ts.Ticks); | |
public static readonly TimeSpanInterval Milliseconds = new TimeSpanInterval("Milliseconds", TimeSpan.FromMilliseconds, ts => ts.TotalMilliseconds); | |
public static readonly TimeSpanInterval Seconds = new TimeSpanInterval("Seconds", TimeSpan.FromSeconds, ts => ts.TotalSeconds); | |
public static readonly TimeSpanInterval Minutes = new TimeSpanInterval("Minutes", TimeSpan.FromMinutes, ts => ts.TotalMinutes); | |
public static readonly TimeSpanInterval Hours = new TimeSpanInterval("Hours", TimeSpan.FromHours, ts => ts.TotalHours); | |
public static readonly TimeSpanInterval Days = new TimeSpanInterval("Days", TimeSpan.FromDays, ts => ts.TotalDays); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment