Wednesday, April 6, 2011

How to get the same time and Day next month using DateTime in c#

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

From stackoverflow
  • 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;
        }
    }
    
    BCS : Kevin got the fastest gun award (I accepted it before anyone even commented on it) The upshot is that his answer got me the info I need even if it wasn't totally correct.
  • 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();   
        }
    }
    

0 comments:

Post a Comment