I am working on an algorithm in C # to calculate the past DateTime based on an input string with the following characteristics:
The string contains an integer followed by either "D", "M", or "Y", for example, "1D" or "90M".
The output will be DateTime.Now minus the corresponding number of days, months, or years.
The problem I am facing is that, for example, I switch the input line to Regex (D, M or Y) and subtract the corresponding TimeSpan from DateTime.Now, the new TimeSpan () constructor does not accept months or years, only days .
if (new Regex(@"[0-9]+D").IsMatch(value)) { newDate = DateTime.Now - TimeSpan(Int32.Parse(value.Replace("D", "")), 0, 0); }
This logic is perfect if the input string is in days, but the constructor for TimeSpan does not accept months or years, and it would be incredibly inaccurate if I assumed that every month had 30 days or every year had 365 days.
Does anyone have any thoughts on how to implement this algorithm?
Thanks!
c # datetime timespan
Nick vaccaro
source share