Add 1 week to current date

前端 未结 3 502
慢半拍i
慢半拍i 2021-01-04 06:56

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

相关标签:
3条回答
  • 2021-01-04 07:29

    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");
    
    0 讨论(0)
  • 2021-01-04 07:30

    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
    0 讨论(0)
  • 2021-01-04 07:30

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

    DateTime.Now.AddDays(7)
    
    0 讨论(0)
提交回复
热议问题