w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Find the first day of the month against a given date

Secondary Nav

C# Sharp DateTime : Exercise-54 with Solution

Write a program in C# Sharp to find the first day of the month against a given date.

Test Data:
Input the Day : 16
Input the Month : 06
Input the Year : 2016
Expected Output :

The formatted Date is : 16/06/2016                                     
 The first day of the month for the above date is : 01/06/2016

C# Sharp Code:

using System;

class dttimeex54
{
    static void Main()
    {
	int yr,mn,dt;
    Console.Write("\n\n Find the first day of the month against a given date :\n");
	Console.Write("-----------------------------------------------------------\n");
	
	Console.Write(" Input the Day : ");
    dt = Convert.ToInt32(Console.ReadLine());	
    Console.Write(" Input the Month : ");
    mn = Convert.ToInt32(Console.ReadLine());	
    Console.Write(" Input the Year : ");
    yr = Convert.ToInt32(Console.ReadLine());		
	DateTime d = new DateTime(yr, mn, dt);
	Console.WriteLine(" The formatted Date is : {0}",d.ToString("dd/MM/yyyy"));
	Console.WriteLine(" The first day of the month for the above date is : {0}\n", FirstDayOfMonth(d).ToString("dd/MM/yyyy"));
    }
    public static DateTime FirstDayOfMonth(DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }
}

C# Sharp Practice online:

using System;

class dttimeex54
{
    static void Main()
    {
	int yr,mn,dt;
    Console.Write("\n\n Find the first day of the month against a given date :\n");
	Console.Write("-----------------------------------------------------------\n");
	
	Console.Write(" Input the Day : ");
    dt = Convert.ToInt32(Console.ReadLine());	
    Console.Write(" Input the Month : ");
    mn = Convert.ToInt32(Console.ReadLine());	
    Console.Write(" Input the Year : ");
    yr = Convert.ToInt32(Console.ReadLine());		
	DateTime d = new DateTime(yr, mn, dt);
	Console.WriteLine(" The formatted Date is : {0}",d.ToString("dd/MM/yyyy"));
	Console.WriteLine(" The first day of the month for the above date is : {0}\n", FirstDayOfMonth(d).ToString("dd/MM/yyyy"));
    }
    public static DateTime FirstDayOfMonth(DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program