I\'ve got something like this DateTime.Now.ToString(\"dd.MM.yy\");
In my code, And I need to add 1 week to it, like 5.4.2012
to become 12.4.2
You want to leave it as a DateTime
until you are ready to convert it to a string.
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
First, always keep the data in it's native type until you are ready to either display it or serialize it (for example, to JSON or to save in a file). You wouldn't convert two int
variables to strings before adding or multiplying them, so don't do it with dates either.
Staying in the native type has a few advantages, such as storing the DateTime
internally as 8 bytes, which is smaller than most of the string formats. But the biggest advantage is that the .NET Framework gives you a bunch of built in methods for performing date and time calculations, as well as parsing datetime values from a source string. The full list can be found here.
So your answer becomes:
DateTime.Now
. Use DateTime.Now.Date
if you'd rather use midnight than the current time.AddDays(7)
to calculate one week later. Note that this method automatically takes into account rolling over to the next month or year, if applicable. Leap days are also factored in for you.// Current local server time + 7 days
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
// Midnight + 7 days
DateTime.Now.Date.AddDays(7).ToString("dd.MM.yy");
And there are plenty of other methods in the framework to help with:
TimeSpan
class for working with time intervalsAny reason you can't use the AddDays method as in
DateTime.Now.AddDays(7)