S Andrew
S Andrew

Reputation: 7298

Adding days to only date and then subtracting it from date in c#

I know this topic has already been discussed but I want to add days to only date, not the complete datetime and then I need to subtract it with date. What I have done till now is :

string endDate = DateTime.Now.AddDays(2).ToShortDateString();

Now this gives me string like 19-jan-17 which is great but when I want to subtract it with todays date, it gives error because the end date is in string. I tried below code:

TimeSpan diff = DateTime.Now.ToShortDateString() - endDate ;

or

TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToDateTime(endDate)

or

TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToString(endDate)

and if I change DateTime.Now.ToShortDateString() to DateTime.Now then it will also include time which I do not want. I just want to add days in date only and then subtract it with today's date.

Any suggestions. Please help.

Upvotes: 0

Views: 1647

Answers (3)

Hudgi
Hudgi

Reputation: 518

I join Federico, you need to use the Date property of the DateTime instance. It will return the 00:00:00 moment of the date.

One side note: Just keep all dates in DateTime (e.g. do not convert them into strings) before calculating the diff. e.g.:

TimeSpan diff = DateTime.Now.Date - endDate; 

If you need the date part, you can use format strings after the calculation. e.g.:

endDate.ToString("yyyy.MM.dd")

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82534

Try this:

DateTime endDate = DateTime.Today.AddDays(2);

TimeSpan diff = DateTime.Today - endDate

The Today property will return only the date part (so time will be 00:00:00), but still in a DateTime struct, so you can get a TimeSpan from subtracting another DateTime from it.

Upvotes: 1

Federico Alecci
Federico Alecci

Reputation: 914

Did you try doing the following?

string endDate = DateTime.Now.Date.AddDays(2);

Still, it is not clear why you have to do that. A bit of context would be great for proposing other solutions.

Upvotes: 1

Related Questions