I am in some trouble within a simple timing manipulation in C#.
The user defines two DateTime
objects, as the start and the end of a time interval:
DateTime From = new DateTime(Y, Mo, D, H, Mi, S, Ms);
DateTime To = new DateTime(YY, MMo, DD, HH, MMi, SS, MMs);
Then a delay parameter, is which a TimeSpan
object, would be taken into account:
TimeSpan delay = new TimeSpan(day, month, hour, second);
Now the program should return the deviation of the time interval, corresponding to the delay
parameter.
Now, there are two problems:
1- Time span has no Year
and Month
parameters, whereas the difference between From
and To
might be more than Day
... How can I feed Year
and Month
into the TimeSpan
object?!... (I know that there is no defined constructor for this aim)
2- The final difference, which I try to catch by below code snippet just produces garbage:
var diff = (To - From).duration() - delay;
How should I resolve this case?!
I am appreciated if anyone can handle above cases...
This is the sort of thing that my Noda Time project is designed to handle. It has a Period
type which does know about months and years, not just a fixed number of ticks. For example:
LocalDateTime start = new LocalDateTime(2014, 1, 1, 8, 30);
LocalDateTime end = new LocalDateTime(2014, 9, 16, 12, 0);
Period delay = new PeriodBuilder {
Months = 8,
Days = 10,
Hours = 2,
Minutes = 20
}
.Build();
Period difference = (Period.Between(start, end) - delay).Normalize();
Here difference
would be a period of 5 days, 1 hour, 10 minutes. (The Normalize()
call is to normalize all values up to days... otherwise you can have "1 hour - 10 minutes" for example.) The Period
API is going to change a bit for Noda Time 2.0, but it will still have the same basic ideas.)
See more on this question at Stackoverflow