Is there any easy way to increment a DateTime by monthly/yearly/daily units without having to parse it out like crazy?

I need to set up billing cycles and process payments. So for example I will process a payment immediately and then set the next one up to process exactly one month from then.

So if I get DateTime.Now is there any quick way to just add a month to it? how about a year? Or will I need to parse it out into MM, YYYY, DD, and then add to MM, if MM == 12 increment year, etc… then piece it back together for my string to submit to this paypal plugin?

Here is the final format needed:

"YYYY-MM-DDTHH:MM:SS.MSZ".

This is explained in more detail below:




YYYY Four-digit year, e.g. "2005" 
MM  Two-digit month. 
DD Two-digit day. 
T Indicates time follows the date. 
HH Hours in military time (24-hour format). 
MM  Minutes 
SS Seconds 
MS Milliseconds 
Z 1-character (US military) representation of the time zone, "A" - "M" are negative offsets -1 to -12, with "J" not being used. "N" - "Y" are positive offsets 1 to 12, and "Z" indicates GMT/UTC (no offset).  


For instance, "2004-05-26T15:00:00.00Z" is May 26th, 2004 at 3:00pm GMT.

So basically I am wondering if there are any easy built in ways to add one month or one year to a date without parsing the crap out of it as a string.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this:

DateTime myDateTime = DateTime.Now.AddMonths(1);

Method 2

DateTime has a set of Add methods such as:

  • AddYears
  • AddMonths
  • AddDays
  • AddHours
  • AddMonths

etc.

More information at DateTime methods.

Method 3

The aptly-named “AddMonths” method comes immediately to mind.

Method 4

If you ever need to work with Quarter or WeekOfYear, Microsoft.VisualBasic.DateAndTime.

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime_members.aspx

Otherwise, System.DateTime does everything you would typically need.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x