Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 501
MetaGuru Avatar asked Sep 30 '09 14:09

MetaGuru


4 Answers

Try this:

DateTime myDateTime = DateTime.Now.AddMonths(1);
like image 162
Matthew Jones Avatar answered Nov 17 '22 08:11

Matthew Jones


DateTime has a set of Add methods such as:

  • AddYears
  • AddMonths
  • AddDays
  • AddHours
  • AddMonths

etc.

More information at DateTime methods.

like image 41
Alfred Myers Avatar answered Nov 17 '22 10:11

Alfred Myers


The aptly-named "AddMonths" method comes immediately to mind.

like image 4
Eric Lippert Avatar answered Nov 17 '22 10:11

Eric Lippert


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.

like image 1
Axl Avatar answered Nov 17 '22 10:11

Axl