Finding the First and Last Day Of A Month in C#

Introduction

If you've ever been tasked with finding records where they fall into a specific month, you can use the following method to calculate the first and last day of any month

using System;

class Program
{
    static void Main()
    {
        int month = 9; // Example month (September)
        int year = 2023; // Example year

        DateTime firstDayOfMonth;
        DateTime lastDayOfMonth;

        GetMonthBoundaries(month, year, out firstDayOfMonth, out lastDayOfMonth);

        Console.WriteLine("First day of the month: " + firstDayOfMonth.ToLongDateString());
        Console.WriteLine("Last day of the month: " + lastDayOfMonth.ToLongDateString());

        Console.ReadLine(); // Keep the console window open
    }

    static void GetMonthBoundaries(int month, int year, out DateTime firstDayOfMonth, out DateTime lastDayOfMonth)
    {
        // Get the 1st day of the month (always day 1)
        DateTime first = new DateTime(year, month, 1);

        // Calculate the last day of the month
        DateTime last = first.AddMonths(1).AddSeconds(-1);

        // Set the out parameters
        firstDayOfMonth = first;
        lastDayOfMonth = last;
    }
}

Output

output


Similar Articles