Calculating past datetime in C#
Asked Answered
B

5

6

I am working on an algorithm in C# to calculate a past DateTime based on an input string with the following characteristics:

The string contains an integer followed by either 'D', 'M' or 'Y', such as "1D" or "90M".

The output will be DateTime.Now minus the corresponding number of days, months or years.

The issue I am having is that if, for instance, I switch the input string on a 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 fine 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 each month had 30 days, or each year had 365 days.

Does anyone have thoughts on how to implement this algorithm?

Thanks!

Beuthen answered 1/3, 2010 at 20:58 Comment(1)
Do you have any thoughts on how to implement it? Because so far, your technique looks like: "ask on SO and maybe someone will do it for me". Tell us what you've tried already!Galaxy
D
15

DateTime has AddMonths, AddDays and AddYears methods. Use them with minus to substract

Decarburize answered 1/3, 2010 at 21:2 Comment(1)
For some awesomely awful reason, I figured that I needed to use a SubtractDays, etc, method to do that. Turns out that adding negatives has the same effect. I may have to retake a basic algebra course... TY!!!Beuthen
C
3

Could you not rather try using the AddDays/AddMonths/AddYears but with negative numbers?

From DateTime.AddDays Method

The value parameter can be negative or positive.

And then maybe just implement a switch stament to apply the appropriate Add method.

Canine answered 1/3, 2010 at 21:3 Comment(0)
T
0

To subtract months, I create a new DateTime and just evaluate month/year. So 1/2010 - 6 months would be 6/2010... once you have the month/year established, you can look at the original datetime day component, and ensure it fits within the month.

That's what I did. Year was evaluated the same way. Subtracting days is easy; use the TimeSpan component to do it.

Tiliaceous answered 1/3, 2010 at 21:2 Comment(0)
M
0

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

Moten answered 1/3, 2010 at 21:4 Comment(0)
D
0

http://msdn.microsoft.com/en-us/library/3z48198e.aspx TimeSpan.TryParse accepts very close to your string as long as you can fits its formatting OR convert from yours to its.

Dorsy answered 1/3, 2010 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.