Get the start and end date of a given week, this month and this week

How can I get the start and end date of a given year (int), a given month (int) and a given week (int) {example Year: 2011 Month: 07 week: 04} in C # 4.0? Thanks in advance.

The start date of the year 2011 is Month 07 and the week number is 04.

+6
source share
5 answers

Google is your friend.

Months:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, 1); } public DateTime LastDayOfMonthFromDateTime(DateTime dateTime) { DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1); return firstDayOfTheMonth.AddMonths(1).AddDays(-1); } 

You can do something like this for years:

  DateTime time = new DateTime(2011,1,1); time.AddYears(1).AddDays(-1); 

And week you need to use CultureInfo.FirstDay (or what you want to set as the first day of the week, in some countries on Monday, sometimes Sunday).

 /// <summary> /// Returns the first day of the week that the specified /// date is in using the current culture. /// </summary> public static DateTime GetFirstDayOfWeek(DateTime dayInWeek) { CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture; return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo); } /// <summary> /// Returns the first day of the week that the specified date /// is in. /// </summary> public static DateTime GetFirstDayOfWeek(DateTime dayInWeek, CultureInfo cultureInfo) { DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek; DateTime firstDayInWeek = dayInWeek.Date; while (firstDayInWeek.DayOfWeek != firstDay) firstDayInWeek = firstDayInWeek.AddDays(-1); return firstDayInWeek; } 
+9
source

Not sure, but is that so after?

 var weekStart = new DateTime(year, month, 1).AddDays(week * 7); var weekEnd = weekStart.AddDays(6); 
0
source

Assuming you start from week 1:

 var startDate = new DateTime(year, month, 1).AddDays((week - 1) * 7); var endDate = startDate.AddDays(6); 
0
source

You can also use

 DateTime.DaysInMonth(int year,int month); 

to understand this. These weeks will be harder.

0
source

DateTime calculations, as they are a bit complicated, with some assumptions I could come up with this

 //assign it to the first day of the month DateTime getweek = new DateTime(2011, 4, 1); // say the week starts on a Sunday while (getweek.DayOfWeek != DayOfWeek.Sunday) getweek = getweek.AddDays(1); DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo; Calendar cal = info.Calendar; //Now you are on the first week add 3 more to move to the Fourth week DateTime start = cal.AddWeeks(getweek, 3); // 24 April 2011 DateTime end = start.AddDays(6); // 30 April 2011 
0
source

Source: https://habr.com/ru/post/893855/


All Articles