Loading ...

C#: Get first and last date of a month | CodeAsp.Net

C#: Get first and last date of a month

 /5
0 (0votes)

If you want to get first and last date of month based on input date following code will help you:

        public static DateTime FirstDayOfMonth(DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, 1);
        }

        public static DateTime LastDayOfMonth(DateTime dateTime)
        {
            var firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
            return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
        }

Here is the full code to test the same:

using System;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Input date
            DateTime dateTime = DateTime.Now;

            DateTime firstDate = FirstDayOfMonth(dateTime);
            DateTime lastDate = LastDayOfMonth(dateTime);

            Console.WriteLine(firstDate);
            Console.WriteLine(lastDate);

            Console.ReadLine();

        }

        public static DateTime FirstDayOfMonth(DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, 1);
        }

        public static DateTime LastDayOfMonth(DateTime dateTime)
        {
            var firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
            return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
        }
    }
}

Comments (no comments yet)

Top Posts