C# DateTime: Scaling Double to Time
I have a function that returns a step size from a bounded range. So if the range is {1,2,3,4,5,6..10} and I want 5 steps it would return a step size of 2. This isn't that complicated.
If I have {.1,.2,.3,.4....1} and I want 7 steps the step size is 0.14285. I then want to convert 0.14285 to the nearest relevant time measurement. In this case .14285 represents a fractional day. For example, the integer 1 would represent a whole day and .25 would repre开发者_StackOverflow社区sent 6 hours.
.14285 = 12,342.24 seconds = 205.704 Minutes = 3.42 Hours ~= 4 hours.
I then want to snap .14285 to (4*60*60 = 14,400 / (24*60*60)) = .16666 which is the decimal equivalent of 4 hours.
I more or less have the math figured out, but I'm wondering if there is an easier way of doing this using DateTime stuff?
I do recommend that you make your question clearer; it took me a while to realize that the 0.14285
you were referring to represented a fraction of a day.
You can use something like this:
// {03:25:42.24}
TimeSpan unSnapped = TimeSpan.FromDays(0.14285);
// {04:00:00} : Round up the hours and construct a TimeSpan from it
TimeSpan snapped = TimeSpan.FromHours(Math.Ceiling(unSnapped.TotalHours));
// 0.166666666
double snappedFractionOfADay = snapped.TotalDays;
You can inspect the TotalXXX
properties on the time-spans to get the other information you mention, if needed.
精彩评论