CSharp - Write program to Read Date and Display the first and last days of that month


Read a date from user input.

Display the first and last days of the month in which the entered date falls.


You get a DateTime object from the user using the Convert.ToDateTime method call.

You can get the month and year numbers from the entered date via the Month and Year properties.

To get the last day of the month, add a month and subtract a day!


using System;
class Program{/*from   ww w  .j a  v  a 2  s. c  o m*/
    static void Main(string[] args){
        // Date input 
        Console.Write("Enter a date: ");
        string input = Console.ReadLine();
        DateTime enteredDate = Convert.ToDateTime(input);

        // Calculations 
        int enteredYear = enteredDate.Year;
        int enteredMonth = enteredDate.Month;

        DateTime firstDayOfMonth = new DateTime(enteredYear, enteredMonth, 1);
        DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

        Console.WriteLine("Corresponding month: " +
            "from " + firstDayOfMonth.ToShortDateString() +
            " to " + lastDayOfMonth.ToShortDateString());