python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Add Month to Current Date C#

5 Best Ways to Add Month To Current Date [How to Add in C#?]

I have a date (2017-04-14) and want to add 1 month to this date using AddMonths(1) and the resulting date is 2017-05-14.

DateTime.Now.AddMonths(1); // 2017-04-14

Example as,
public static class DateTime_Extensions
    //METHOD 1
    public static DateTime AddMonthsCustom(this DateTime source, int months)
        DateTime result = source.AddMonths(months);
        if (source.Day != DateTime.DaysInMonth(source.Year, source.Month))
            return result;

   //METHOD 2
    public static DateTime AddMonths(this DateTime date)
         if (date.Day != DateTime.DaysInMonth(date.Year, date.Month))
            return date.AddMonths(1);
           return date.AddMonths(1);

    //METHOD 3
    public static DateTime AddSmartMonths(this DateTime date, int nMonths)
        int year = date.Year;
        int month = date.Month;
        int day = date.Day;

        if ((day == 30) && (day < DateTime.DaysInMonth(year, month)))
            date = date.AddDays(1);
        else if ((month == 1) && (day > 28))
            date = new DateTime(year, month, 31);

        return date.AddMonths(nMonths);

I hope you are enjoying with this post! Please share with you friends. Thank you so much!

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions