C# – Logic for calculating dates based on a given timeframe


Sometimes, we get requirements where we need to calculate start date and end date based on a given timeframe. I have used following method for one of such cases when I had to calculate dates based on “Current day” /”Current month” … etc. Here is the code snippet for those who would want to reuse:

 

/// <summary>
/// Gets the dates from time frame.
/// </summary>
/// <param name="timeFrame">The time frame.</param>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
private void GetDatesFromTimeFrame(string timeFrame, out DateTime startDate, out DateTime endDate)
{
    switch (timeFrame)
    {
        case "Current day":
            TimeSpan s = DateTime.Now.TimeOfDay;
            startDate = DateTime.Now.Add(-s);
            endDate = DateTime.Now;
            break;
        case "Current month":
            startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-(DateTime.Now.Day - 1));
            endDate = DateTime.Now;
            break;
        case "Current week":
            switch (DateTime.Now.DayOfWeek.ToString())
            {
                case "Monday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-1);
                    break;
                case "Tuesday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-2);
                    break;
                case "Wednesday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-3);
                    break;
                case "Thursday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-4);
                    break;
                case "Friday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-5);
                    break;
                case "Saturday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-6);
                    break;
                case "Sunday":
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay);
                    break;
                default:
                    startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay);
                    break;
            }

            endDate = DateTime.Now;
            break;
        case "Current year":
            startDate = DateTime.Now.Add(-DateTime.Now.TimeOfDay).Date.AddDays(-(DateTime.Now.DayOfYear - 1));
            endDate = DateTime.Now;
            break;
        default:
            startDate = DateTime.Now.AddDays(-1);
            endDate = DateTime.Now;
            break;
    }
}

Comments (1)

  1. Surabhi says:

    This is good. Thansk for the code snippet.

Skip to main content