C# Code Snippet - Find starting and ending date for given date

C# Code Snippet - Find starting and ending date for given date

C# Code Snippet - Find starting and ending date for given date

(C-Sharp) C# code snippets return the Ending Date and Starting Date for given date. Simply pass DateTime value that need to find date and snippets will return starting and ending date as DateTime.

Bookmark:

C# Code Snippet - Find starting and ending date for given date

These .Net C# code snippets return the Ending Date and Starting Date for given date. Simply pass the DateTime value and these methods return the appropriate starting ending date values as a DateTime format.

Following code snippet returns ending date for given date.

/// <summary>
/// Get end date of given month
/// </summary>
/// <param name="_Date">Date to find end date</param>
/// <returns>DateTime of end date of the month</returns>
public DateTime EndDateOfMonth(DateTime _Date)
{
    if (_Date != null)
        return new DateTime(_Date.Year, _Date.Month, 1).AddMonths(1).AddDays(-1);
    else
        return _Date;
}


Following code snippet returns starting date for given date.

/// <summary>
/// Get starting date of given month
/// </summary>
/// <param name="_Date">Date to find starting date</param>
/// <returns>DateTime of starting date of the month</returns>
public DateTime StartDateOfMonth(DateTime _Date)
{
    if (_Date != null)
        return new DateTime(_Date.Year, _Date.Month, 1);
    else
        return _Date;
}


Here is a simple example showing how to use above functions (EndDateOfMonth / StartDateOfMonth) to get ending and starting date for given date.

Console.WriteLine("End date of the month : " + EndDateOfMonth(DateTime.Now).ToString());
Console.WriteLine("Start date of the month : " + StartDateOfMonth(DateTime.Now).ToString());


C# Keywords Used:

  • DateTime
  • DateTime.AddDays
  • DateTime.AddMonths

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, DateTime, Starting date, Ending date, Date conversion, AddDays, AddMonths, DateTime Methods
  • Programming Language : C# (C-Sharp)

External Resources:

Kiran :: August 02-2009 :: 08:03 AM

Great work man!!!!!!. Making it an extension method will add more beauty.......

Leave a comment