René Beneš
René Beneš

Reputation: 468

Add 1 week to current date

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.2012 I tried to convert it to int and then add it up, but there is a problem when it's up to 30.

Can you tell me some clever way how to do it?

Upvotes: 15

Views: 45452

Answers (3)

mgnoonan
mgnoonan

Reputation: 7200

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

Upvotes: 7

Dan P
Dan P

Reputation: 1999

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

DateTime.Now.AddDays(7)

Upvotes: 2

Guvante
Guvante

Reputation: 19203

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");

Upvotes: 36

Related Questions