HOWTO: Determine first day of week

DayPilot Pro contains a helper class that calculates the date of the first day of week from any date.

DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek();

There are several methods/signatures you can call:

  • Week.FirstDayOfWeek() - first day of this week, using the current culture settings
  • Week.FirstDayOfWeek(DateTime day) - first day of a week that contains the specified day, using the current culture settings
  • Week.FirstDayOfWeek(DateTime day, DayOfWeek weekStarts) - first day of a week that contains a specified day, using weekStarts as the first day of week
  • Week.FirstWorkingDayOfWeek(DateTime day) - first Monday of the specified week

The source code:

/// <summary>
/// Helper class for determining first day of week.
/// </summary>
public class Week
{
/// <summary>
/// Gets the first day of this week. Based on current culture.
/// </summary>
/// <returns></returns>
public static DateTime FirstDayOfWeek()
{
return FirstDayOfWeek(DateTime.Today);
}
/// <summary>
/// Gets the first day of a week where day (parameter) belongs. Based on current culture.
/// </summary>
/// <returns></returns>
public static DateTime FirstDayOfWeek(DateTime day)
{
return FirstDayOfWeek(day, Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
}
/// <summary>
/// Gets the first day of a week where day (parameter) belongs. weekStart (parameter) specifies the starting day of week.
/// </summary>
/// <returns></returns>
public static DateTime FirstDayOfWeek(DateTime day, DayOfWeek weekStarts)
{
DateTime d = day;
while (d.DayOfWeek != weekStarts)
{
d = d.AddDays(-1);
}
return d;
}
/// <summary>
/// Returns Monday of the week where day (parameter) belongs.
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
public static DateTime FirstWorkingDayOfWeek(DateTime day)
{
return FirstDayOfWeek(day, DayOfWeek.Monday);
}
}

DayPilot for JavaScript, ASP.NET WebForms, ASP.NET MVC, Java