Calculating date and time in C #

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!

+6
c # datetime timespan
source share
5 answers

DateTime has AddMonths , AddDays and AddYears . Use them with a minus to subtract

+15
source share

Could you try using AddDays / AddMonths / AddYears, but with negative numbers?

From DateTime.AddDays Method

The value parameter can be negative or positive.

And then maybe just apply the switch line to apply the appropriate Add method.

+3
source share

To subtract the months, I create a new DateTime and just evaluate the month / year. Thus, 1/2010 - 6 months will be 6/2010 ... Once you have set the month / year, you can look at the original component of the day of the day and ensure its consistency over the course of the month.

What I've done. The year was estimated equally. Subtracting days is easy; use the TimeSpan component to do this.

0
source share

Remember that you can add negative amounts and check this method and this one .

0
source share

http://msdn.microsoft.com/en-us/library/3z48198e.aspx TimeSpan.TryParse takes very close to your line if you can adapt its formatting OR convert from yours to yours.

0
source share

All Articles