Add 1 week to current date

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:

  • Get the current timestamp from DateTime.Now. Use DateTime.Now.Date if you'd rather use midnight than the current time.
  • Use 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.
  • Convert the result to a string using your desired format
// 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:

  • Internationalization
  • UTC and timezones (though you might want to check out NodaTime for more advanced applications)
  • Operator overloading for some basic math calcs
  • The TimeSpan class for working with time intervals

Any reason you can't use the AddDays method as in

DateTime.Now.AddDays(7)

Tags:

C#

Datetime