简体   繁体   中英

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

I have ac# 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

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;
    }
}

This works for me:

    DateTime d = DateTime.Now;
    d.AddMonths(1);
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();   
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM