Reputation: 78635
I have a c# DateTime object and I need to increment it by one month.
example:
input output
-------------------------------
Jan 12, 2005 Feb 12, 2005
Feb 28, 2009 Mar 28, 2009
Dec 31, 2009 Jan 31, 2010
Jan 29, 2000 Feb 29, 2000
Jan 29, 2100 Error: no Feb 29, 2100
What is the best way to do this.
My first thought (aside from some built in code) was to construct a new DateTime from pieces and handle the roll to the year myself
Upvotes: 2
Views: 6689
Reputation: 852
This works for me:
DateTime d = DateTime.Now;
d.AddMonths(1);
Upvotes: 1
Reputation: 13266
using System;
public static class Test
{
public static void Main()
{
string[] dates = { "Jan 12, 2005", "Feb 28, 2009", "Dec 31, 2009", "Jan 29, 2000", "Jan 29, 2100" };
foreach (string date in dates)
{
DateTime t1 = DateTime.Parse(date);
DateTime t2 = t1.AddMonths(1);
if (t1.Day != t2.Day)
Console.WriteLine("Error: no " + t2.ToString("MMM") + " " + t1.Day + ", " + t2.Year);
else
Console.WriteLine(t2.ToString("MMM dd, yyyy"));
}
Console.ReadLine();
}
}
Upvotes: 1
Reputation: 1502446
Here's a complete program showing the examples given in the question. You'd probably want to use an exception in OneMonthAfter if it really shouldn't be called that way.
using System;
using System.Net;
public class Test
{
static void Main(string[] args)
{
Check(new DateTime(2005, 1, 12));
Check(new DateTime(2009, 2, 28));
Check(new DateTime(2009, 12, 31));
Check(new DateTime(2000, 1, 29));
Check(new DateTime(2100, 1, 29));
}
static void Check(DateTime date)
{
DateTime? next = OneMonthAfter(date);
Console.WriteLine("{0} {1}", date,
next == null ? (object) "Error" : next);
}
static DateTime? OneMonthAfter(DateTime date)
{
DateTime ret = date.AddMonths(1);
if (ret.Day != date.Day)
{
// Or throw an exception
return null;
}
return ret;
}
}
Upvotes: 6