How To Find The First Date Of A Week From A Given Date In C#

Hello, in this blog we will write a program in a C# console application that accepts three parameters: the day, month, and year of a given date and returns the first date of the week based on that date.

Code

using System;
using System.Globalization;

namespace FirstDateOfWeek
{
    class Program
    {
        static void Main(string[] args)
        {
            int yr, mn, dt;
            Console.Write("\n\n Find the first day of a week against a given date :\n");
            Console.Write("--------------------------------------------------------\n");

            Console.Write(" Enter the Day : ");
            dt = Convert.ToInt32(Console.ReadLine());
            Console.Write(" Enter the Month : ");
            mn = Convert.ToInt32(Console.ReadLine());
            Console.Write(" Enter 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"));
            var culture = CultureInfo.CurrentCulture;
            var diff = d.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
            if (diff < 0)
                diff += 7;
            d = d.AddDays(-diff).Date;
            Console.WriteLine(" The first day of the week for the above date is : {0}\n", d.ToString("dd/MM/yyyy"));
            Console.ReadKey();
        }
    }
}

Explanation

  • In the preceding code, we first collect user input as day, month, and year.
  • Then we translate the user’s inputs into correct dates and display them.
  • Then we have System’s current culture. GlobalizationCultureInfo. Please visit the Microsoft website for the most up-to-date culture information.
  • Following that, we obtain the difference between the day of the week of our input date and the first day of the week of current culture.
  • If the difference is less than zero (0), we add 7 to it. Because we subtract the difference of the days from the given date in the following line, and if it returns a negative number, it becomes positive, because we also pass minus (-) before diff in AddDays() methods.
  • The AddDays() method adds days to a specified date, but when a negative value is passed, it subtracts the supplied days.

Output

In the above image, you can see that I input 15 December 2021, and it returned 12 December 2021, which is the first day of the week, as shown in the calendar image.

Because Sunday is the default first day of the week on my local computer, it returns a date with Sunday as the first day of the week. If I modify the first day of the week in the setting, it returns the appropriate date.

Thanks

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories