In this article we create a program in c# console application which takes three parameter day of the date, month of the date and year of the date, and then we get the first date of week from that date.
Code
Explanation
- In above code first we take input from user as day, month and year.
- Then convert those inputs into proper date and show to user.
- Then get current culture from System.GlobalizationCultureInfo. Please check official documentation for current culture info on Microsoft website.
- After this, get the difference from day of the week of our input date and first day of the week of current culture.
- If difference is less than zero (0) than we add 7 in that difference. Because in next line we minus that difference days from given date and if pass negative value than it became positive value because we also pass minus (-) before diff in AddDays() methods.
- AddDays() method add days in given date, but here we pass negative value, so it subtracts given days.
Output
In above image you can see that I entered 15 Dec 2021, and it returns 12 Dec 2021 which is first date of week as you can check in given calendar image.
In my local pc it is by default Sunday as a first day of week, so it returns date considering Sunday as a first day of week. If I change first day of week from setting, then it returns date as per that.
0 Comments