DateTimeExtensions Class
Definition
Provides calendar-arithmetic, period-anchoring, ISO-aware, and tick-level operations over DateTime for code that outgrows the BCL surface - fiscal calendars, ISO 8601 week numbering, weekend rules, and high-throughput tick math.
public static class DateTimeExtensions
- Inheritance
-
DateTimeExtensions
- Inherited Members
Remarks
DateTime exposes raw fields and a handful of arithmetic operators but leaves the harder calendar work - locating the first Monday of a quarter, snapping to the start or end of a day, computing ISO weeks, or converting between time zones and epochs - to the caller. This class concentrates that work in a single, allocation-aware extension surface so that scheduling, reporting, and calendar-driven code does not need to drop down to Calendar or hand-rolled tick math.
The API surface groups into: period anchors (FirstDateOfMonth, FirstDateOfQuarter,
LastDateOfYear and the matching LastDateOf… set), day-boundary helpers (StartOfDay,
EndOfDay, Midday, Midnight, Truncate), weekday navigation (NextDateOfWeek,
PreviousDateOfWeek, NearestDateOfWeek, NextWeekday, NthDateOfWeekInMonth), period
predicates and numbering (IsLeapYear, IsWeekend, IsInRange, WeekOfMonth,
WeekOfYear, IsoWeekOfYear, IsoYear, Quarter), and conversions (ToDateOnly,
ToDateTimeOffset, ToIsoString, ToTimeSpan, the UnixTime/epoch family).
Many helpers operate directly on Ticks to avoid intermediate DateTime
allocations and favor method-impl AggressiveInlining for hot-path calendar code. Operations that read culture
data (DayName, MonthName, ISO week calculations against a
CultureInfo) accept the culture explicitly or fall back to
CurrentCulture; pure date arithmetic is culture-neutral and
deterministic. The Kind of the input is preserved unless an explicit conversion is
requested. ArgumentOutOfRangeException is thrown whenever a result would leave the supported
DateTime range.
When compiled with a tool-chain that supports C# 14 extension members, the parameterless predicate and
scalar-accessor helpers are exposed as extension properties (for example dateTime.IsFirstDateOfMonth);
otherwise they compile as classic extension methods (for example dateTime.IsFirstDateOfMonth()).
var dt = new DateTime(2025, 4, 30, 14, 35, 0, DateTimeKind.Utc);
// Snap to the start and end of the same day, preserving Kind.
DateTime startOfDay = dt.StartOfDay(); // 2025-04-30T00:00:00Z
DateTime endOfDay = dt.EndOfDay(); // 2025-04-30T23:59:59.9999999Z
// ISO 8601 week-of-year and matching ISO year.
int isoWeek = dt.IsoWeekOfYear; // 18
int isoYear = dt.IsoYear; // 2025
// Walk to the first Monday strictly after this date.
DateTime nextMonday = dt.NextDateOfWeek(DayOfWeek.Monday); // 2025-05-05T14:35:00Z
Methods
Add(DateTime, int, int, double)
Returns a new DateTime obtained by adding the specified number of years, months, and fractional
days to the supplied dateTime.
public static DateTime Add(this DateTime dateTime, int years, int months, double days)
Parameters
dateTimeDateTimeThe date and time value to which the offsets are applied.
yearsintThe number of calendar years to add. A negative value subtracts years.
monthsintThe number of calendar months to add. A negative value subtracts months.
daysdoubleThe number of days to add, including fractional values. A negative value subtracts days.
Returns
- DateTime
An object whose value is the result of adding the specified number of years, months, and days to
dateTime, with the original Kind preserved.
Remarks
Adjustments are applied in the order years, then months, then days. When the resulting day does not exist in the target month (e.g. February 30), the date is clamped to the last valid day of that month, accounting for leap years and varying month lengths.
The days parameter supports fractional values, applied with tick-level precision. Values
smaller than 1e-10 are ignored. The original time-of-day is preserved unless days includes a
fractional component, in which case the time is adjusted accordingly.
This method performs all adjustments using tick arithmetic and does not rely on AddYears(int), AddMonths(int), or AddDays(double), making it suitable for performance-critical paths.
Examples:
var dt1 = new DateTime(2023, 1, 31);
var result1 = dt1.Add(0, 1, 0); // → 2023-02-28 (non-leap year)
var dt2 = new DateTime(2020, 1, 31);
var result2 = dt2.Add(0, 1, 0); // → 2020-02-29 (leap year)
var dt3 = new DateTime(2023, 3, 15, 10, 30, 0);
var result3 = dt3.Add(1, -2, 10.75); // → 2024-01-25 19:30:00
var dt4 = new DateTime(2022, 10, 5, 8, 0, 0);
var result4 = dt4.Add(0, 0, -2.5); // → 2022-10-02 20:00:00
var dt5 = new DateTime(2024, 2, 29);
var result5 = dt5.Add(1, 0, 0); // → 2025-02-28 (2025 is not a leap year)
Exceptions
- ArgumentOutOfRangeException
Thrown if the resulting date is earlier than MinValue or later than MaxValue.
AddFiscalYears(DateTime, int, IQuarterDefinitionProvider)
Returns a new DateTime obtained by advancing or retreating dateTime by the
signed number of fiscal years specified in count, preserving the time-of-day and
Kind.
public static DateTime AddFiscalYears(this DateTime dateTime, int count, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe starting date and time.
countintThe signed number of fiscal years to apply.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
- DateTime
The date/time offset by
countfiscal years.
Exceptions
- ArgumentNullException
Thrown when
provideris null.
Age(DateTime)
Returns the age in full calendar years between the specified dateTime and
Today.
public static int Age(this DateTime dateTime)
Parameters
dateTimeDateTimeThe earlier date to calculate from, typically representing a birth date or other reference point.
Returns
- int
The number of full calendar years that have elapsed between
dateTimeand Today. Returns0ifdateTimeoccurs after today.
Remarks
This overload determines the number of full years that have passed by comparing the year, month, and day
components. If the month and day of dateTime have not yet occurred in the current year, the
result is decremented by one.
If dateTime is February 29 in a leap year and today is not a leap year, the comparison is
performed as if the date were February 28.
The result is clamped to 0 to avoid returning negative values when dateTime is in the
future. The Kind property is ignored when calculating the result.
Age(DateTime, DateTime)
Returns the age in full calendar years between the specified dateTime and a supplied
reference date.
public static int Age(this DateTime dateTime, DateTime atDate)
Parameters
dateTimeDateTimeThe earlier date to calculate from, typically representing a birth date or other reference point.
atDateDateTimeThe later date to calculate to, representing the point in time at which the age is evaluated.
Returns
- int
The number of full calendar years that have elapsed between
dateTimeandatDate. Returns0ifatDateoccurs beforedateTime.
Remarks
This overload determines the number of full years that have passed by comparing the year, month, and day
components. If the month and day of dateTime have not yet occurred in the year of
atDate, the result is decremented by one.
If dateTime is February 29 in a leap year and atDate is in a non-leap
year, the comparison is performed as if the date were February 28.
The result is clamped to 0 to avoid returning negative values when dateTime is after
atDate. The Kind property is ignored when calculating the result.
DayName(DateTime)
Returns the full name of the day of the week for the specified DateTime, using the formatting rules of CurrentCulture.
public static string DayName(this DateTime dateTime)
Parameters
Returns
- string
A string containing the localized full day name, formatted using CurrentCulture.
Remarks
This overload uses the GetDayName(DayOfWeek) method of the current culture to retrieve the day name. For culture-specific results, use the DayName(DateTime, CultureInfo?) overload.
DayName(DateTime, CultureInfo?)
Returns the full name of the day of the week for the specified DateTime, using the formatting rules of the supplied or current culture.
public static string DayName(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value whose DayOfWeek is used to determine the name.
cultureCultureInfoAn optional CultureInfo used to format the result. If null, CurrentCulture is used.
Returns
- string
A string containing the localized full day name for
dateTime, formatted using the supplied or current culture.
Remarks
This overload uses the GetDayName(DayOfWeek) method of the supplied or current culture to retrieve the day name.
DaysInMonth(DateTime)
Returns the number of days in the calendar month of the specified DateTime, using the proleptic Gregorian calendar.
public static int DaysInMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year and month are used to determine the result.
Returns
- int
The total number of days in the specified month and year of
dateTime, based on the GregorianCalendar.
Remarks
This overload always evaluates the result using the proleptic Gregorian calendar, regardless of the current culture or calendar settings. For culture-specific results, use the DaysInMonth(DateTime, CultureInfo?) or DaysInMonth(DateTime, Calendar?) overload.
DaysInMonth(DateTime, Calendar?)
Returns the number of days in the calendar month of the specified DateTime, using the supplied or current culture's calendar.
public static int DaysInMonth(this DateTime dateTime, Calendar? calendar)
Parameters
dateTimeDateTimeThe date and time value whose year and month are used to determine the result.
calendarCalendarAn optional Calendar instance used to evaluate the result. If null, the Calendar of CurrentCulture is used.
Returns
- int
The total number of days in the specified month and year of
dateTime, based on the rules of the supplied or current calendar.
Remarks
This overload supports calendar-aware computations for systems such as HebrewCalendar,
HijriCalendar, JapaneseCalendar, and others supported by .NET.
dateTime is first projected into the target calendar, so the result is equivalent to
calendar.GetDaysInMonth(calendar.GetYear(dateTime), calendar.GetMonth(dateTime)) - the length of the
calendar's own month containing the date, not the Gregorian month. If calendar is
null, the Calendar of
CurrentCulture is used.
This method does not account for leap months. For calendars that support leap months or multiple eras, consider
using GetDaysInMonth(year, month, era) instead.
DaysInMonth(DateTime, CultureInfo?)
Returns the number of days in the calendar month of the specified DateTime, using the calendar associated with the supplied culture.
public static int DaysInMonth(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value whose year and month are used to determine the result.
cultureCultureInfoAn optional CultureInfo that supplies the calendar. If null, CurrentCulture is used.
Returns
- int
The total number of days in the specified month and year of
dateTime, based on the calendar ofculture.
Remarks
This overload retrieves the Calendar from the culture's
Calendar property and returns the number of days in the month of that
calendar's own year/month reckoning that contains dateTime, i.e.
calendar.GetDaysInMonth(calendar.GetYear(dateTime), calendar.GetMonth(dateTime)).
This is useful when working with cultures that use non-Gregorian calendars such as HebrewCalendar or HijriCalendar. If the calendar supports leap months or eras, this method does not account for them explicitly. For precise control, use the overload that accepts a Calendar directly.
DaysInYear(DateTime)
Returns the number of days in the calendar year of the specified DateTime, using the calendar of CurrentCulture.
public static int DaysInYear(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
Returns
- int
The total number of days in the year of
dateTime, as defined by the calendar of CurrentCulture.
Remarks
This overload uses the calendar the current culture is set to use: the Calendar of CurrentCulture, which is not necessarily the culture's default Calendar. The result may vary depending on the calendar system (e.g. Gregorian, Hebrew, Hijri).
DaysInYear(DateTime, Calendar?)
Returns the number of days in the calendar year of the specified DateTime, using the supplied or current calendar.
public static int DaysInYear(this DateTime dateTime, Calendar? calendar)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
calendarCalendarAn optional Calendar used to evaluate the result. If null, the Calendar of CurrentCulture is used.
Returns
- int
The number of days in the year of
dateTime, based on the supplied or fallback calendar.
Remarks
Use this overload when you want to explicitly calculate based on a specific calendar system (e.g.
GregorianCalendar, HebrewCalendar). If calendar is
null, the Calendar of
CurrentCulture is used.
dateTime is first projected into the target calendar, so the result is equivalent to
calendar.GetDaysInYear(calendar.GetYear(dateTime)) - the length of the calendar's own year containing the
date, not the Gregorian year.
ElapsedTimeSince(DateTime)
Returns a TimeSpan representing the time that has elapsed between the specified
dateTime and UtcNow.
public static TimeSpan ElapsedTimeSince(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to compare against UtcNow. Must have a Kind of either Utc or Local.
Returns
- TimeSpan
The signed time interval between
dateTimeand the current UTC time; that is, UtcNow minusdateTime.
Remarks
If dateTime is in local time (Local), it is converted to UTC
using ToUniversalTime() before comparison. Unspecified values
are rejected to avoid ambiguity regarding the time zone context.
Exceptions
- ArgumentException
Thrown if
dateTimehas a Kind of Unspecified.
EndOfDay(DateTime)
Returns a new DateTime representing the end of the calendar day (23:59:59.9999999) that contains
the specified dateTime.
public static DateTime EndOfDay(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose date is preserved while the time is set to the final tick of the day.
Returns
- DateTime
An object whose value is set to 23:59:59.9999999 on the same calendar day as
dateTime, with the original Kind preserved.
Remarks
The result is calculated by extracting the date component of dateTime and adding
TicksPerDay - 1 to represent the last representable moment of the day - one tick before midnight of the
next day.
Example:
var dt = new DateTime(2024, 7, 7, 10, 30, 0);
var result = dt.EndOfDay(); // → 2024-07-07 23:59:59.9999999
FirstDateOfFiscalYear(int, IQuarterDefinitionProvider)
Returns the first calendar day of the supplied fiscal year under the supplied IQuarterDefinitionProvider.
public static DateTime FirstDateOfFiscalYear(int fiscalYear, IQuarterDefinitionProvider provider)
Parameters
fiscalYearintThe fiscal year whose start date is requested.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
Exceptions
- ArgumentNullException
Thrown when
provideris null.
FirstDateOfMonth(DateTime)
Returns a new DateTime representing the first day of the same calendar month and year as the
specified dateTime.
public static DateTime FirstDateOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year and month are used to determine the result.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the same calendar month and year as
dateTime, with the original Kind preserved.
Remarks
This method calculates the first day of the month using Gregorian calendar rules.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Example:
var dt = new DateTime(2025, 7, 15, 14, 45, 0);
var result = dt.FirstDateOfMonth(); // → 2025-07-01 00:00:00
FirstDateOfQuarter(DateTime)
Returns a new DateTime representing the first day of the calendar quarter that contains the
specified dateTime, using the standard calendar quarter definition.
public static DateTime FirstDateOfQuarter(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the quarter that contains
dateTime, with the original Kind preserved.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember:
- Q1January - March
- Q2April - June
- Q3July - September
- Q4October - December
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
FirstDateOfQuarter(DateTime, CalendarQuarterDefinition)
Returns a new DateTime representing the first day of the quarter that contains the specified
dateTime, using the specified calendar quarter definition.
public static DateTime FirstDateOfQuarter(this DateTime dateTime, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the corresponding quarter, with the original Kind preserved.
Remarks
The definition controls whether quarters are aligned to the first day of a month (e.g.
January - March) or anchored to a custom day-of-month boundary.
For provider-driven (e.g. 4-4-5 fiscal) quarters, use the FirstDateOfQuarter(DateTime, IQuarterDefinitionProvider) overload instead.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
FirstDateOfQuarter(DateTime, IQuarterDefinitionProvider)
Returns a new DateTime representing the first day of the quarter that contains the specified
dateTime, using a custom IQuarterDefinitionProvider.
public static DateTime FirstDateOfQuarter(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the quarter containing
dateTime, with the original Kind preserved.
Remarks
This overload supports advanced or domain-specific quarter systems by delegating boundary logic to the supplied
provider - for example, 4-4-5 retail calendars or regional fiscal quarters.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentNullException
Thrown if
provideris null.- ArgumentOutOfRangeException
Thrown if the
providerreturns a date outside the range of MinValue and MaxValue.
FirstDateOfWeek(DateTime)
Returns a new DateTime representing the first day of the week that contains the specified
dateTime, using the first day of the week defined by
CurrentCulture.
public static DateTime FirstDateOfWeek(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the culturally defined first day of the week containing
dateTime, with the original Kind preserved.
Remarks
This overload uses CurrentCulture to determine the first day of the week, based on FirstDayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
FirstDateOfWeek(DateTime, WorkingDaysOfWeek)
Returns a new DateTime representing the first day of the week that contains the specified
dateTime, using a start-of-week inferred from the specified WorkingDaysOfWeek
.
public static DateTime FirstDateOfWeek(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
workingWeekWorkingDaysOfWeekA WorkingDaysOfWeek used to infer the first day of the week. For example, MondayToFriday implies a Monday start.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the week containing
dateTime, with the original Kind preserved.
Remarks
The method infers the start of the week based on the specified workingWeek value. If
AllDays is supplied, the method defaults to using
Monday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined WorkingDaysOfWeek value, -or- the resulting date is earlier than MinValue or later than MaxValue.
FirstDateOfWeek(DateTime, CultureInfo?)
Returns a new DateTime representing the first day of the week that contains the specified
dateTime, using the first day of the week defined by the supplied or current culture.
public static DateTime FirstDateOfWeek(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
cultureCultureInfoAn optional CultureInfo that defines the first day of the week via FirstDayOfWeek. If null, CurrentCulture is used.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the culturally defined first day of the week containing
dateTime, with the original Kind preserved.
Remarks
This method computes the day offset between dateTime and the culture-specific first day of
the week, subtracts that offset, and resets the time to midnight.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if the resulting date is earlier than MinValue or later than MaxValue.
FirstDateOfWeekInMonth(DateTime, DayOfWeek)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the same calendar month and year as the specified dateTime.
public static DateTime FirstDateOfWeekInMonth(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value whose month and year are used to determine the result.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Monday returns the first Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the same calendar month and year asdateTime, with the original Kind preserved.
Remarks
The search begins on the first day of the month and proceeds forward to locate the first matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
FirstDateOfWeekInQuarter(DateTime, DayOfWeek)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the calendar quarter that contains the specified dateTime,
using the standard calendar quarter definition.
public static DateTime FirstDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the first Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember. The search begins on the first day of the quarter and proceeds forward to locate the first matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
FirstDateOfWeekInQuarter(DateTime, DayOfWeek, CalendarQuarterDefinition)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the quarter that contains the specified dateTime, using the
supplied calendar quarter definition.
public static DateTime FirstDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the first Monday.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
The start of the quarter is computed using definition, and the search proceeds forward to
the first date that matches the specified dayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
FirstDateOfWeekInQuarter(DateTime, DayOfWeek, IQuarterDefinitionProvider)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the quarter that contains the specified dateTime, using a
custom IQuarterDefinitionProvider.
public static DateTime FirstDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the first Monday.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
The start of the quarter is determined by the supplied provider, and the search proceeds
forward to the first date that matches the specified dayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentNullException
Thrown if
provideris null.- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
FirstDateOfWeekInYear(DateTime, DayOfWeek)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the same calendar year as the specified dateTime.
public static DateTime FirstDateOfWeekInYear(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the year. For example, Monday returns the first Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the same calendar year asdateTime, with the original Kind preserved.
Remarks
The search begins on January 1 of the year and proceeds forward to locate the first matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
FirstDateOfYear(DateTime)
Returns a new DateTime representing the first day of the same calendar year as the specified
dateTime.
public static DateTime FirstDateOfYear(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on January 1 of the same calendar year as
dateTime, with the original Kind preserved.
Remarks
This method calculates the first day of the year using Gregorian calendar rules.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Example:
var dt = new DateTime(2025, 7, 15, 14, 45, 0);
var result = dt.FirstDateOfYear(); // → 2025-01-01 00:00:00
FiscalYear(DateTime, IQuarterDefinitionProvider)
Returns the fiscal year that contains the supplied DateTime under the supplied IQuarterDefinitionProvider.
public static int FiscalYear(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date to identify.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
- int
The fiscal year number under the provider's conventions.
Exceptions
- ArgumentNullException
Thrown when
provideris null.
FromDayOfYear(int, int)
Returns a new DateTime representing midnight on the dayOfYear-th day of the
specified year.
public static DateTime FromDayOfYear(int year, int dayOfYear)
Parameters
Returns
- DateTime
A DateTime value set to midnight (00:00:00) on the date that is the
dayOfYear-th day ofyear, with Unspecified.
Remarks
This method is the inverse of the DayOfYear property. Day numbering is one-based, so day
1 is January 1 and the final day (365 in a common year, 366 in a leap year) is December 31.
The returned value always carries a time-of-day of midnight.
The mapping depends on whether year is a leap year: day 60 resolves to February 29 in
a leap year but to March 1 in a common year.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than 1 or greater than 9999, -or-dayOfYearis less than 1 or greater than the number of days inyear(365 in a common year, 366 in a leap year).
FromUnixTimeMilliseconds(long)
Returns a new DateTime representing the point in time corresponding to the specified Unix timestamp, expressed in milliseconds since 1970-01-01T00:00:00Z.
public static DateTime FromUnixTimeMilliseconds(long timestamp)
Parameters
timestamplongThe number of milliseconds that have elapsed since the Unix epoch.
Returns
- DateTime
An object whose value is set to the UTC date and time corresponding to
timestamp, with Kind equal to Utc.
Remarks
Use ToUnixTimeMilliseconds(DateTime) to perform the inverse conversion.
Exceptions
- ArgumentOutOfRangeException
Thrown if
timestampis outside the range supported for conversion to DateTime .
- See Also
FromUnixTimeSeconds(long)
Returns a new DateTime representing the point in time corresponding to the specified Unix timestamp, expressed in seconds since 1970-01-01T00:00:00Z.
public static DateTime FromUnixTimeSeconds(long timestamp)
Parameters
timestamplongThe number of seconds that have elapsed since the Unix epoch.
Returns
- DateTime
An object whose value is set to the UTC date and time corresponding to
timestamp, with Kind equal to Utc.
Remarks
Use ToUnixTimeSeconds(DateTime) to perform the inverse conversion.
Exceptions
- ArgumentOutOfRangeException
Thrown if
timestampis outside the range supported for conversion to DateTime .
- See Also
GetDayNumber(DateTime)
Computes the day number corresponding to the specified DateTime, representing the number of days since 0001-01-01.
public static int GetDayNumber(DateTime dateTime)
Parameters
Returns
- int
The number of days elapsed since 0001-01-01, where that date is treated as day 0.
Remarks
This method performs a fast, allocation-free conversion by dividing the Ticks value by the number of ticks per day.
GetDayNumber(int, int, int)
Computes the day number for the specified year, month, and day, representing the number of days elapsed since 0001-01-01.
public static int GetDayNumber(int year, int month, int day)
Parameters
yearintThe year component, which must be between 1 and 9999 inclusive.
monthintThe month component, which must be between 1 and 12 inclusive.
dayintThe day component, which must be valid for the specified year and month.
Returns
Remarks
This method performs full validation of the input parameters to ensure that the specified date is valid in the proleptic Gregorian calendar.
It provides functionality equivalent to computing new DateOnly(year, month, day).DayNumber, but avoids
object allocations and is optimized for scenarios where correctness and validation are both required.
Exceptions
- ArgumentOutOfRangeException
Thrown if
year,month, ordayis outside the valid range of the Gregorian calendar, or if the combination does not form a valid date.
GetFirstDateOfIsoWeek(int, int)
Returns a new DateTime representing the first day (Monday) of the specified ISO 8601 week and year.
public static DateTime GetFirstDateOfIsoWeek(int isoYear, int isoWeek)
Parameters
isoYearintThe ISO 8601 year, defined as the year containing the Thursday of the first ISO week. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.isoWeekintThe ISO 8601 week number to evaluate, ranging from 1 to the number of ISO weeks in the supplied year.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the Monday that begins the specified ISO 8601 week, using Unspecified.
Remarks
This method computes the first day of a given ISO 8601 week by anchoring on January 4 (which always falls in ISO week 1), then backtracking to the preceding Monday and advancing by the supplied number of weeks.
The ISO 8601 calendar follows these rules:
- weeks begin on Monday;
- week 1 is the first week containing at least four days of the new year;
- years contain either 52 or 53 weeks.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
isoYearis less than theYearof MinValue or greater than that of MaxValue, -or-isoWeekis less than 1 or greater than the number of ISO weeks inisoYear.
GetFirstDateOfMonth(int, int)
Returns a new DateTime representing the first day of the specified calendar month and year.
public static DateTime GetFirstDateOfMonth(int year, int month)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the result. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the specified month and year, using Unspecified.
Remarks
This method uses Gregorian calendar rules to determine the resulting date.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-monthis less than 1 or greater than 12.
GetFirstDateOfQuarter(int, int)
Returns a new DateTime representing the first day of the specified calendar
quarter in the given year, using the standard calendar quarter
definition.
public static DateTime GetFirstDateOfQuarter(int year, int quarter)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 (Jan - Mar) through 4 (Oct - Dec).
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the specified quarter and year, using Unspecified.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4.
GetFirstDateOfQuarter(int, int, CalendarQuarterDefinition)
Returns a new DateTime representing the first day of the specified quarter
and year, using the supplied calendar quarter definition.
public static DateTime GetFirstDateOfQuarter(int year, int quarter, CalendarQuarterDefinition definition)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 through 4.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarters are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first day of the specified quarter, using Unspecified.
Remarks
The definition controls whether quarters are aligned to the first day of a month or anchored
to a custom day-of-month boundary.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
quarteris less than 1 or greater than 4, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use a provider-based overload instead.
GetFirstDateOfWeekInMonth(int, int, DayOfWeek)
Returns a new DateTime representing the first occurrence of the specified DayOfWeek within the given calendar month and year.
public static DateTime GetFirstDateOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the result. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Monday returns the first Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the specifiedyearandmonth, using Unspecified.
Remarks
The search begins on the first day of the month and proceeds forward to locate the first matching weekday.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-monthis less than 1 or greater than 12, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration.
GetFirstDateOfWeekInQuarter(int, int, DayOfWeek)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the specified calendar quarter and year,
using the standard calendar quarter definition.
public static DateTime GetFirstDateOfWeekInQuarter(int year, int quarter, DayOfWeek dayOfWeek)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 (Jan - Mar) through 4 (Oct - Dec).
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the first Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the quarter, using Unspecified.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration.
GetFirstDateOfWeekInQuarter(int, int, DayOfWeek, CalendarQuarterDefinition)
Returns a new DateTime representing the first occurrence of the specified
DayOfWeek within the specified quarter and year, using
the supplied calendar quarter definition.
public static DateTime GetFirstDateOfWeekInQuarter(int year, int quarter, DayOfWeek dayOfWeek, CalendarQuarterDefinition definition)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 through 4.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the first Monday.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first occurrence of
dayOfWeekwithin the quarter, using Unspecified.
Remarks
The start of the quarter is computed using definition, and the search proceeds forward to
the first date that matches the specified dayOfWeek.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
GetIsoWeeksInYear(int)
Returns the number of ISO 8601 weeks in the specified year.
public static int GetIsoWeeksInYear(int year)
Parameters
yearintThe ISO 8601 year to evaluate. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.
Returns
- int
The number of ISO 8601 weeks in the supplied year - either 52 or 53.
Remarks
According to ISO 8601, a year contains 53 weeks if either of the following is true:
- January 1 of the supplied year falls on a Thursday;
- December 31 of the supplied year falls on a Thursday (equivalent to January 1 of the following year falling on a Friday).
All other years contain exactly 52 weeks. The implementation evaluates these conditions by computing the weekday of January 1 for the supplied year and the following year, using Bodu.Extensions.DateTimeExtensions.GetDayOfWeekForJanuary1(System.Int32).
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue.
GetLastDateOfIsoWeek(int, int)
Returns a new DateTime representing the last day (Sunday) of the specified ISO 8601 week and year.
public static DateTime GetLastDateOfIsoWeek(int isoYear, int isoWeek)
Parameters
isoYearintThe ISO 8601 year, defined as the year containing the Thursday of the first ISO week. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.isoWeekintThe ISO 8601 week number to evaluate, ranging from 1 to the number of ISO weeks in the supplied year.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the Sunday that ends the specified ISO 8601 week, using Unspecified.
Remarks
This method computes the last day of a given ISO 8601 week by anchoring on January 4 (which always falls in ISO week 1), backtracking to the preceding Monday, advancing by the supplied number of weeks, and adding six days to reach the Sunday of that week.
The ISO 8601 calendar follows these rules:
- weeks begin on Monday and end on Sunday;
- week 1 is the first week containing at least four days of the new year;
- years contain either 52 or 53 weeks.
The returned value is normalized to midnight (00:00:00) and uses Unspecified. For the corresponding start of the week, use GetFirstDateOfIsoWeek(int, int).
Exceptions
- ArgumentOutOfRangeException
Thrown if
isoYearis less than theYearof MinValue or greater than that of MaxValue, -or-isoWeekis less than 1 or greater than the number of ISO weeks inisoYear.
GetLastDateOfMonth(int, int)
Returns a new DateTime representing the last day of the specified calendar month and year.
public static DateTime GetLastDateOfMonth(int year, int month)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the result. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the specified month and year, using Unspecified.
Remarks
This method uses Gregorian calendar rules to determine the number of days in the specified month, including leap-year adjustments for February.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-monthis less than 1 or greater than 12.
GetLastDateOfQuarter(int, int)
Returns a new DateTime representing the last day of the specified calendar
quarter in the given year, using the standard calendar quarter
definition.
public static DateTime GetLastDateOfQuarter(int year, int quarter)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 (Jan - Mar) through 4 (Oct - Dec).
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the specified quarter and year, using Unspecified.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4.
GetLastDateOfQuarter(int, int, CalendarQuarterDefinition)
Returns a new DateTime representing the last day of the specified quarter and
year, using the supplied calendar quarter definition.
public static DateTime GetLastDateOfQuarter(int year, int quarter, CalendarQuarterDefinition definition)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 through 4.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarters are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the specified quarter, using Unspecified.
Remarks
The definition controls whether quarters are aligned to the first day of a month or anchored
to a custom day-of-month boundary.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
quarteris less than 1 or greater than 4, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use a provider-based overload instead.
GetLastDateOfWeekInMonth(int, int, DayOfWeek)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek within the given calendar month and year.
public static DateTime GetLastDateOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the result. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Monday returns the last Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the specifiedyearandmonth, using Unspecified.
Remarks
The search begins on the last day of the month and proceeds backward to locate the last matching weekday.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-monthis less than 1 or greater than 12, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration.
GetLastDateOfWeekInQuarter(int, int, DayOfWeek)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the specified calendar quarter and year, using the standard
calendar quarter definition.
public static DateTime GetLastDateOfWeekInQuarter(int year, int quarter, DayOfWeek dayOfWeek)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 (Jan - Mar) through 4 (Oct - Dec).
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the last Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the quarter, using Unspecified.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration.
GetLastDateOfWeekInQuarter(int, int, DayOfWeek, CalendarQuarterDefinition)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the specified quarter and year, using the supplied calendar
quarter definition.
public static DateTime GetLastDateOfWeekInQuarter(int year, int quarter, DayOfWeek dayOfWeek, CalendarQuarterDefinition definition)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.quarterintThe quarter number, from 1 through 4.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the last Monday.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the quarter, using Unspecified.
Remarks
The end of the quarter is computed using definition, and the search proceeds backward to the
last date that matches the specified dayOfWeek.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-quarteris less than 1 or greater than 4, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
GetMonthName(int)
Returns the full name of the specified calendar month, using the formatting rules of CurrentCulture.
public static string GetMonthName(int month)
Parameters
monthintThe calendar month. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
Returns
- string
A string containing the localized full month name, formatted using CurrentCulture.
Remarks
This overload uses the GetMonthName(int) method of the current culture to retrieve the month name.
Exceptions
- ArgumentOutOfRangeException
Thrown if
monthis less than 1 or greater than 12.
GetMonthName(int, CultureInfo?)
Returns the full name of the specified calendar month, using the formatting rules of the supplied or current culture.
public static string GetMonthName(int month, CultureInfo? culture)
Parameters
monthintThe calendar month. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
cultureCultureInfoAn optional CultureInfo used to format the result. If null, CurrentCulture is used.
Returns
- string
A string containing the localized full month name, formatted using the supplied or current culture.
Remarks
This overload uses the GetMonthName(int) method of the supplied or current culture to retrieve the month name.
Exceptions
- ArgumentOutOfRangeException
Thrown if
monthis less than 1 or greater than 12.
GetNearestDateOfWeek(int, int, int, DayOfWeek)
Returns a new DateTime representing the nearest date (before or after) to the specified calendar
year, month, and day that falls on the given
DayOfWeek.
public static DateTime GetNearestDateOfWeek(int year, int month, int day, DayOfWeek dayOfWeek)
Parameters
yearintThe calendar year of the reference date. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the reference date. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
dayintThe day component of the reference date. Must be valid for the specified
yearandmonth, including leap-year considerations for February.dayOfWeekDayOfWeekThe target DayOfWeek to locate.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the closest date (either before or after) to the specified reference date that falls on the given
dayOfWeek, using Unspecified. If two dates are equally close, the earlier one is returned.
Remarks
The result is computed by evaluating the day-distance between the specified reference date and the nearest
occurrence of dayOfWeek in either direction.
Exceptions
- ArgumentOutOfRangeException
Thrown if
year,month, ordaydoes not represent a valid date, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration.
GetNthDateOfWeekInMonth(int, int, DayOfWeek, WeekOrdinal)
Returns a new DateTime representing the specified ordinal occurrence of a
DayOfWeek within the given calendar month and year.
public static DateTime GetNthDateOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek, WeekOrdinal ordinal)
Parameters
yearintThe calendar year of the result. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.monthintThe calendar month of the result. Must be between 1 and 12, inclusive, where 1 represents January and 12 represents December.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Tuesday returns the nth Tuesday.
ordinalWeekOrdinalThe ordinal occurrence to return. Valid values are First, Second, Third, Fourth, Fifth, and Last. Fifth is valid only in months where five matching weekdays occur.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the requested occurrence of
dayOfWeekwithin the specifiedyearandmonth, using Unspecified.
Remarks
For Last, the method returns the final matching dayOfWeek in the
month. For other ordinal values, the method locates the first matching weekday and offsets by a multiple of
seven days to reach the desired ordinal.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-monthis less than 1 or greater than 12, -or-dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-ordinalis not a defined value of the WeekOrdinal enumeration, -or- the requestedordinaldoes not occur within the month (for example, a fifth Thursday in February).
GetStartDateOfWeek(int, int, CultureInfo?)
Returns a new DateTime representing the first day of the specified culture-defined week number in the given calendar year.
public static DateTime GetStartDateOfWeek(int year, int week, CultureInfo? culture = null)
Parameters
yearintThe calendar year to evaluate. Must be between the
Yearproperty values of MinValue and MaxValue, inclusive.weekintThe culture-defined week number to evaluate, starting at 1. The maximum valid value depends on the CalendarWeekRule and DayOfWeek used by the supplied
culture.cultureCultureInfoAn optional CultureInfo used to determine the CalendarWeekRule and starting DayOfWeek. If null, CurrentCulture is used.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the first date of the specified week in the specified year, using Unspecified.
Remarks
This method uses the culture-defined week numbering system. The start of week 1 depends on the culture's CalendarWeekRule: under FirstDay the (possibly partial) first week begins on January 1 itself; under FirstFullWeek it begins at the first occurrence of the culture's FirstDayOfWeek on or after January 1; and under FirstFourDayWeek it begins at the week boundary of the week containing January 1 when at least four days of that week fall in the new year (which may place the start in the previous December), otherwise one week later. Subsequent weeks advance in 7-day intervals from the week-boundary alignment.
The result is validated by recalculating the week number for the computed date using the internal week-of-year
calculation and comparing it to week. Dates that fall in the previous calendar year (such as
the start of ISO week 1 in late December) are handled correctly.
The returned value is normalized to midnight (00:00:00) and uses Unspecified.
Exceptions
- ArgumentOutOfRangeException
Thrown if
yearis less than theYearof MinValue or greater than that of MaxValue, -or-weekdoes not correspond to a valid week number foryearunder the rules of the supplied or currentculture.
IsFirstDateOfFiscalYear(DateTime, IQuarterDefinitionProvider)
Returns true when dateTime's date component is the first day of its
fiscal year under the supplied IQuarterDefinitionProvider.
public static bool IsFirstDateOfFiscalYear(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe value to test.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
Exceptions
- ArgumentNullException
Thrown when
provideris null.
IsFirstDateOfMonth(DateTime)
Determines whether the specified DateTime falls on the first day of its calendar month.
public static bool IsFirstDateOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
This method evaluates whether the Day component is equal to 1.
IsFirstDateOfQuarter(DateTime)
Determines whether the specified DateTime falls on the first day of its calendar quarter, using the standard calendar quarter definition.
public static bool IsFirstDateOfQuarter(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember: Q1 = Jan - Mar, Q2 = Apr - Jun, Q3 = Jul - Sep, Q4 = Oct - Dec.
The comparison is performed on the date component only; the time component of dateTime is
ignored.
IsFirstDateOfQuarter(DateTime, CalendarQuarterDefinition)
Determines whether the specified DateTime falls on the first day of its calendar quarter, using the supplied calendar quarter definition.
public static bool IsFirstDateOfQuarter(this DateTime dateTime, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
Remarks
The comparison is performed on the date component only; the time component of dateTime is
ignored.
Exceptions
- ArgumentOutOfRangeException
Thrown if
definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
IsFirstDateOfQuarter(DateTime, IQuarterDefinitionProvider)
Determines whether the specified DateTime falls on the first day of its calendar quarter, using a custom IQuarterDefinitionProvider.
public static bool IsFirstDateOfQuarter(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- bool
true if
dateTimerepresents the first day of its quarter as defined byprovider; otherwise, false.
Remarks
The comparison is performed on the date component only; the time component of dateTime is
ignored.
Exceptions
- ArgumentNullException
Thrown if
provideris null.
IsInRange(DateTime, DateTime, DateTime)
Determines whether the specified DateTime falls within the inclusive range defined by
start and end.
public static bool IsInRange(this DateTime dateTime, DateTime start, DateTime end)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
startDateTimeThe inclusive lower bound of the range.
endDateTimeThe inclusive upper bound of the range.
Returns
- bool
true if
dateTimeis greater than or equal tostartand less than or equal toend; otherwise, false.
Remarks
IsInRange(DateTime?, DateTime, DateTime)
Determines whether the specified nullable DateTime falls within the inclusive range defined by
start and end.
public static bool IsInRange(this DateTime? dateTime, DateTime start, DateTime end)
Parameters
dateTimeDateTime?The nullable date and time value to evaluate.
startDateTimeThe inclusive lower bound of the range.
endDateTimeThe inclusive upper bound of the range.
Returns
- bool
true if
dateTimehas a value that is greater than or equal tostartand less than or equal toend; otherwise, false .
Remarks
IsInWorkingWeek(DateTime, WeekPattern)
Determines whether the specified DateTime falls on a day that is selected in the supplied WeekPattern working week.
public static bool IsInWorkingWeek(this DateTime dateTime, WeekPattern workingWeek)
Parameters
dateTimeDateTimeThe date and time to evaluate.
workingWeekWeekPatternThe working-week pattern.
Returns
Remarks
This predicate considers only the day-of-week dimension. It does not consult any holiday catalogue. Combine it with a notable-date service when both working-week and holiday awareness are required.
IsInWorkingWeek(DateTime, WorkingDaysOfWeek)
Determines whether the specified DateTime falls on a day that is selected in the supplied WorkingDaysOfWeek working week.
public static bool IsInWorkingWeek(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe date and time to evaluate.
workingWeekWorkingDaysOfWeekThe named working-week pattern.
Returns
Exceptions
- ArgumentOutOfRangeException
Thrown when
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.- ArgumentException
Thrown when
workingWeekis Custom, which has no canonical pattern.
IsLastDateOfFiscalYear(DateTime, IQuarterDefinitionProvider)
Returns true when dateTime's date component is the last day of its fiscal
year under the supplied IQuarterDefinitionProvider.
public static bool IsLastDateOfFiscalYear(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe value to test.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
Exceptions
- ArgumentNullException
Thrown when
provideris null.
IsLastDateOfMonth(DateTime)
Determines whether the specified DateTime falls on the last day of its calendar month.
public static bool IsLastDateOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
This method compares the Day component to the total number of days in the same month and year, accounting for leap-year adjustments to February.
Equivalent to checking whether dateTime.Day == DateTime.DaysInMonth(dateTime.Year, dateTime.Month).
IsLastDateOfQuarter(DateTime)
Determines whether the specified DateTime falls on the last day of its calendar quarter, using the standard calendar quarter definition.
public static bool IsLastDateOfQuarter(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember: Q1 = Jan - Mar, Q2 = Apr - Jun, Q3 = Jul - Sep, Q4 = Oct - Dec.
The comparison is performed on the date component only; the time component of dateTime is
ignored.
IsLastDateOfQuarter(DateTime, CalendarQuarterDefinition)
Determines whether the specified DateTime falls on the last day of its calendar quarter, using the supplied calendar quarter definition.
public static bool IsLastDateOfQuarter(this DateTime dateTime, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
Remarks
The comparison is performed on the date component only; the time component of dateTime is
ignored.
Exceptions
- ArgumentOutOfRangeException
Thrown if
definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
IsLastDateOfQuarter(DateTime, IQuarterDefinitionProvider)
Determines whether the specified DateTime falls on the last day of its calendar quarter, using a custom IQuarterDefinitionProvider.
public static bool IsLastDateOfQuarter(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- bool
true if
dateTimerepresents the last day of its quarter as defined byprovider; otherwise, false.
Remarks
The comparison is performed on the date component only; the time component of dateTime is
ignored.
Exceptions
- ArgumentNullException
Thrown if
provideris null.
IsLeapYear(DateTime)
Determines whether the year of the specified DateTime is a leap year, according to the proleptic Gregorian calendar.
public static bool IsLeapYear(this DateTime dateTime)
Parameters
Returns
Remarks
This method applies the Gregorian leap-year rules:
- Years divisible by 4 are leap years,
- except years divisible by 100,
- unless also divisible by 400.
For example, the years 2000 and 2024 are leap years, while 1900 and 2100 are not.
This method does not consider culture-specific calendars; it always evaluates leap years using the Gregorian calendar.
IsRestDay(DateTime, WeekPattern)
Determines whether the specified DateTime falls on a day that is not selected in the supplied WeekPattern working week.
public static bool IsRestDay(this DateTime dateTime, WeekPattern workingWeek)
Parameters
dateTimeDateTimeThe date and time to evaluate.
workingWeekWeekPatternThe working-week pattern.
Returns
Remarks
This predicate is the complement of IsInWorkingWeek(DateTime, WeekPattern) and considers only the day-of-week dimension. It does not consult any holiday catalogue.
IsRestDay(DateTime, WorkingDaysOfWeek)
Determines whether the specified DateTime falls on a day that is not selected in the supplied WorkingDaysOfWeek working week.
public static bool IsRestDay(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe date and time to evaluate.
workingWeekWorkingDaysOfWeekThe named working-week pattern.
Returns
Exceptions
- ArgumentOutOfRangeException
Thrown when
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.- ArgumentException
Thrown when
workingWeekis Custom, which has no canonical pattern.
IsWeekday(DateTime)
Determines whether the specified DateTime falls on a weekday, using the default MondayToFriday rule.
public static bool IsWeekday(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
A weekday is any day selected by the working-week pattern. This overload uses MondayToFriday and no custom provider.
IsWeekday(DateTime, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Determines whether the specified DateTime falls on a weekday, using the supplied
WorkingDaysOfWeek and an optional custom provider.
public static bool IsWeekday(this DateTime dateTime, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider = null)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom.
Returns
Remarks
The method evaluates whether the DayOfWeek of dateTime is included
in the working-week pattern supplied by workingWeek and optionally refined by
provider.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration, -or-workingWeekis Custom andprovideris null.
IsWeekday(DayOfWeek, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Determines whether the specified DayOfWeek is considered a weekday, using the supplied
WorkingDaysOfWeek and an optional custom provider.
public static bool IsWeekday(DayOfWeek dayOfWeek, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider = null)
Parameters
dayOfWeekDayOfWeekThe DayOfWeek value to evaluate.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom.
Returns
Remarks
This method is equivalent to !IsWeekend(dayOfWeek, workingWeek, provider).
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration, -or-workingWeekis Custom andprovideris null.
IsWeekend(DateTime)
Determines whether the specified DateTime falls on a weekend, using the default MondayToFriday rule.
public static bool IsWeekend(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
Remarks
This overload uses the standard working-week pattern (Monday through Friday), so Saturday and Sunday are treated as weekend days.
IsWeekend(DateTime, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Determines whether the specified DateTime falls on a weekend, using the supplied
WorkingDaysOfWeek and an optional custom provider.
public static bool IsWeekend(this DateTime dateTime, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider = null)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days. Any day not selected is treated as a weekend day.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom.
Returns
- bool
true if
dateTimefalls on a weekend day as defined by the supplied working-week or provider; otherwise, false.
Remarks
This method supports alternative working-week patterns used in different cultures and regions, such as Sunday-to-Thursday or Saturday-to-Wednesday.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration, -or-workingWeekis Custom andprovideris null.
IsWeekend(DayOfWeek, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Determines whether the specified DayOfWeek is considered a weekend day, using the supplied
WorkingDaysOfWeek and an optional custom provider.
public static bool IsWeekend(DayOfWeek dayOfWeek, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider = null)
Parameters
dayOfWeekDayOfWeekThe DayOfWeek value to evaluate.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days. Any day not selected is treated as a weekend day.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom.
Returns
Remarks
This overload supports custom weekend evaluation logic via provider when
workingWeek is Custom. For all other values the result is
derived from the canonical WeekPattern implied by workingWeek.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-workingWeekis not a defined value of the WorkingDaysOfWeek enumeration, -or-workingWeekis Custom andprovideris null.
IsoWeekOfYear(DateTime)
Returns the ISO 8601 week number for the specified dateTime.
public static int IsoWeekOfYear(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
- int
An integer in the range 1 - 53 representing the ISO 8601 week number that contains
dateTime.
Remarks
This method follows the ISO 8601 standard for week numbering, where:
- weeks begin on Monday;
- week 1 is the first week containing at least four days of the new year.
The result is computed using FirstFourDayWeek and
Monday against the date portion of dateTime. Any time-of-day
component is discarded before the calculation.
IsoYear(DateTime)
Returns the ISO 8601 year associated with the specified date.
public static int IsoYear(this DateTime date)
Parameters
dateDateTimeThe date and time value to evaluate.
Returns
- int
The ISO 8601 calendar year that contains the ISO week of
date.
Remarks
The ISO 8601 year may differ from the calendar year of date. A date near the start or end of
a calendar year may belong to the ISO year of the adjacent calendar year, depending on which ISO week it falls
into. For example, January 1 may belong to the last week of the previous ISO year, and December 31 may belong to
week 1 of the following ISO year.
LastDateOfFiscalYear(int, IQuarterDefinitionProvider)
Returns the last calendar day of the supplied fiscal year under the supplied IQuarterDefinitionProvider.
public static DateTime LastDateOfFiscalYear(int fiscalYear, IQuarterDefinitionProvider provider)
Parameters
fiscalYearintThe fiscal year whose end date is requested.
providerIQuarterDefinitionProviderThe provider that defines the fiscal year boundaries.
Returns
Exceptions
- ArgumentNullException
Thrown when
provideris null.
LastDateOfMonth(DateTime)
Returns a new DateTime representing the last day of the same calendar month and year as the
specified dateTime.
public static DateTime LastDateOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year and month are used to determine the result.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the same calendar month and year as
dateTime, with the original Kind preserved.
Remarks
This method calculates the last day of the month using Gregorian calendar rules. Leap years are correctly accounted for when determining the length of February.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Example:
var dt = new DateTime(2024, 2, 15, 14, 45, 0);
var result = dt.LastDateOfMonth(); // → 2024-02-29 00:00:00
LastDateOfQuarter(DateTime)
Returns a new DateTime representing the last day of the calendar quarter that contains the
specified dateTime, using the standard calendar quarter definition.
public static DateTime LastDateOfQuarter(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the quarter that contains
dateTime, with the original Kind preserved.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember:
- Q1January - March
- Q2April - June
- Q3July - September
- Q4October - December
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
LastDateOfQuarter(DateTime, CalendarQuarterDefinition)
Returns a new DateTime representing the last day of the quarter that contains the specified
dateTime, using the specified calendar quarter definition.
public static DateTime LastDateOfQuarter(this DateTime dateTime, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the corresponding quarter, with the original Kind preserved.
Remarks
The definition controls whether quarters are aligned to the first day of a month (e.g.
January - March) or anchored to a custom day-of-month boundary.
For provider-driven (e.g. 4-4-5 fiscal) quarters, use the LastDateOfQuarter(DateTime, IQuarterDefinitionProvider) overload instead.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
LastDateOfQuarter(DateTime, IQuarterDefinitionProvider)
Returns a new DateTime representing the last day of the quarter that contains the specified
dateTime, using a custom IQuarterDefinitionProvider.
public static DateTime LastDateOfQuarter(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the quarter containing
dateTime, with the original Kind preserved.
Remarks
This overload supports advanced or domain-specific quarter systems by delegating boundary logic to the supplied
provider - for example, 4-4-5 retail calendars or regional fiscal quarters.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentNullException
Thrown if
provideris null.- ArgumentOutOfRangeException
Thrown if the
providerreturns a date outside the range of MinValue and MaxValue.
LastDateOfWeek(DateTime)
Returns a new DateTime representing the last day of the week that contains the specified
dateTime, using the last day of the week defined by
CurrentCulture.
public static DateTime LastDateOfWeek(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the culturally defined last day of the week containing
dateTime, with the original Kind preserved.
Remarks
This overload uses CurrentCulture to determine the last day of the week, inferred from FirstDayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
LastDateOfWeek(DateTime, WorkingDaysOfWeek)
Returns a new DateTime representing the last day of the week that contains the specified
dateTime, using a start-of-week inferred from the specified WorkingDaysOfWeek
.
public static DateTime LastDateOfWeek(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
workingWeekWorkingDaysOfWeekA WorkingDaysOfWeek used to infer the last day of the week. For example, MondayToFriday implies a Monday start (and therefore a Sunday end).
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last day of the week containing
dateTime, with the original Kind preserved.
Remarks
The method infers the start of the week based on the specified workingWeek value, then
calculates the last day as six days after the inferred start. If AllDays is
supplied, the method defaults to using Monday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined WorkingDaysOfWeek value, -or- the resulting date is earlier than MinValue or later than MaxValue.
LastDateOfWeek(DateTime, CultureInfo?)
Returns a new DateTime representing the last day of the week that contains the specified
dateTime, using the last day of the week defined by the supplied or current culture.
public static DateTime LastDateOfWeek(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing week.
cultureCultureInfoAn optional CultureInfo that defines the first day of the week via FirstDayOfWeek. If null, CurrentCulture is used.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the culturally defined last day of the week containing
dateTime, with the original Kind preserved.
Remarks
This method computes the day offset between dateTime and the culture-specific last day of
the week, adds that offset, and resets the time to midnight.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if the resulting date is earlier than MinValue or later than MaxValue.
LastDateOfWeekInMonth(DateTime, DayOfWeek)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the same calendar month and year as the specified dateTime.
public static DateTime LastDateOfWeekInMonth(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value whose month and year are used to determine the result.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Monday returns the last Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the same calendar month and year asdateTime, with the original Kind preserved.
Remarks
The search begins on the last day of the month and proceeds backward to locate the last matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
LastDateOfWeekInQuarter(DateTime, DayOfWeek)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the calendar quarter that contains the specified dateTime, using the standard
calendar quarter definition.
public static DateTime LastDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the last Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember. The search begins on the last day of the quarter and proceeds backward to locate the last matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
LastDateOfWeekInQuarter(DateTime, DayOfWeek, CalendarQuarterDefinition)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the quarter that contains the specified dateTime, using the supplied calendar quarter
definition.
public static DateTime LastDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the last Monday.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how quarter boundaries are aligned.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
The end of the quarter is computed using definition, and the search proceeds backward to the
last date that matches the specified dayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
LastDateOfWeekInQuarter(DateTime, DayOfWeek, IQuarterDefinitionProvider)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the quarter that contains the specified dateTime, using a custom
IQuarterDefinitionProvider.
public static DateTime LastDateOfWeekInQuarter(this DateTime dateTime, DayOfWeek dayOfWeek, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value used to determine the containing quarter.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the quarter. For example, Monday returns the last Monday.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the quarter, with the original Kind preserved.
Remarks
The end of the quarter is determined by the supplied provider, and the search proceeds
backward to the last date that matches the specified dayOfWeek.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentNullException
Thrown if
provideris null.- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
LastDateOfWeekInYear(DateTime, DayOfWeek)
Returns a new DateTime representing the last occurrence of the specified DayOfWeek
within the same calendar year as the specified dateTime.
public static DateTime LastDateOfWeekInYear(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the year. For example, Monday returns the last Monday.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the last occurrence of
dayOfWeekwithin the same calendar year asdateTime, with the original Kind preserved.
Remarks
The search begins on December 31 of the year and proceeds backward to locate the last matching weekday.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
LastDateOfYear(DateTime)
Returns a new DateTime representing the last day of the same calendar year as the specified
dateTime.
public static DateTime LastDateOfYear(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose year is used to determine the result.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on December 31 of the same calendar year as
dateTime, with the original Kind preserved.
Remarks
This method calculates the last day of the year using Gregorian calendar rules.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Example:
var dt = new DateTime(2025, 7, 15, 14, 45, 0);
var result = dt.LastDateOfYear(); // → 2025-12-31 00:00:00
Max(DateTime, DateTime)
Returns the later of two specified DateTime values.
public static DateTime Max(DateTime first, DateTime second)
Parameters
firstDateTimeThe first DateTime value to compare.
secondDateTimeThe second DateTime value to compare.
Returns
Remarks
This method compares the two values using the greater-than-or-equal-to (>=) operator, which is
equivalent to CompareTo(DateTime). The Kind of the selected
value is preserved.
Max(DateTime?, DateTime?)
Returns the later of two specified nullable DateTime values.
public static DateTime? Max(DateTime? first, DateTime? second)
Parameters
firstDateTime?The first nullable DateTime value to compare.
secondDateTime?The second nullable DateTime value to compare.
Returns
Remarks
Midday(DateTime)
Returns a new DateTime representing midday (12:00:00) on the same calendar day as the specified
dateTime.
public static DateTime Midday(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose date is preserved while the time is set to midday.
Returns
- DateTime
An object whose value is set to 12:00:00.000 on the same calendar day as
dateTime, with the original Kind preserved.
Remarks
This method replaces the time component of the input with exactly 12:00 PM (noon) while retaining the date and Kind of the input. The returned value contains no fractional seconds or milliseconds.
Example:
var dt = new DateTime(2025, 7, 15, 14, 45, 0);
var result = dt.Midday(); // → 2025-07-15 12:00:00
Midnight(DateTime)
Returns a new DateTime representing midnight (00:00:00) on the same calendar day as the specified
dateTime.
public static DateTime Midnight(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose date is preserved while the time is reset to midnight.
Returns
- DateTime
An object whose value is set to 00:00:00 on the same calendar day as
dateTime, with the original Kind preserved.
Remarks
This method is functionally equivalent to StartOfDay(DateTime) and to accessing Date. It normalizes the time component to midnight while retaining the date and Kind of the input.
Example:
var dt = new DateTime(2025, 7, 15, 14, 45, 0);
var result = dt.Midnight(); // → 2025-07-15 00:00:00
Min(DateTime, DateTime)
Returns the earlier of two specified DateTime values.
public static DateTime Min(DateTime first, DateTime second)
Parameters
firstDateTimeThe first DateTime value to compare.
secondDateTimeThe second DateTime value to compare.
Returns
Remarks
This method compares the two values using the less-than-or-equal-to (<=) operator, which is equivalent
to CompareTo(DateTime). The Kind of the selected value is
preserved.
Min(DateTime?, DateTime?)
Returns the earlier of two specified nullable DateTime values.
public static DateTime? Min(DateTime? first, DateTime? second)
Parameters
firstDateTime?The first nullable DateTime value to compare.
secondDateTime?The second nullable DateTime value to compare.
Returns
Remarks
MonthName(DateTime)
Returns the full name of the month for the specified DateTime, using the formatting rules of CurrentCulture.
public static string MonthName(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose month component is used to determine the name.
Returns
- string
A string containing the localized full month name, formatted using CurrentCulture.
Remarks
This overload uses the GetMonthName(int) method of the current culture to retrieve the month name. For culture-specific results, use the MonthName(DateTime, CultureInfo?) overload.
MonthName(DateTime, CultureInfo?)
Returns the full name of the month for the specified DateTime, using the formatting rules of the supplied or current culture.
public static string MonthName(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value whose month component is used to determine the name.
cultureCultureInfoAn optional CultureInfo used to format the result. If null, CurrentCulture is used.
Returns
- string
A string containing the localized full month name for
dateTime, formatted using the supplied or current culture.
Remarks
This overload uses the GetMonthName(int) method of the supplied or current culture to retrieve the month name.
NearestDateOfWeek(DateTime, DayOfWeek)
Returns a new DateTime representing the nearest date (before or after) to the specified
dateTime that falls on the given DayOfWeek.
public static DateTime NearestDateOfWeek(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe reference date and time value.
dayOfWeekDayOfWeekThe target DayOfWeek to locate.
Returns
- DateTime
An object whose value is set to the closest date (either before or after) to
dateTimethat falls on the specifieddayOfWeek, with the original time-of-day and Kind preserved. If two dates are equally close, the earlier one is returned.
Remarks
The result is computed by evaluating the day-distance between dateTime and the nearest
occurrence of dayOfWeek in either direction.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
NextDateOfWeek(DateTime, DayOfWeek)
Returns a new DateTime representing the next calendar occurrence of the specified
DayOfWeek after the given dateTime.
public static DateTime NextDateOfWeek(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search forward.
dayOfWeekDayOfWeekThe DayOfWeek to locate. For example, Monday returns the next Monday.
Returns
- DateTime
An object whose value is set to the next occurrence of
dayOfWeekfollowingdateTime, with the original time-of-day and Kind preserved.
Remarks
If dateTime already falls on the specified dayOfWeek, the result is
exactly seven days later. The method advances forward in time and never returns the original date.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
NextOccurrence(DateTime, TimeSpan, DateTime)
Returns a new DateTime representing the next occurrence of a recurring event that starts at
dateTime and repeats every interval, occurring strictly after the
specified after timestamp.
public static DateTime NextOccurrence(this DateTime dateTime, TimeSpan interval, DateTime after)
Parameters
dateTimeDateTimeThe date and time value representing the initial reference point of the recurring event.
intervalTimeSpanThe fixed TimeSpan between successive occurrences. Must be greater than Zero.
afterDateTimeThe point in time after which the next occurrence must fall.
Returns
- DateTime
An object whose value is the first occurrence of the event that falls strictly after
after, based on the supplieddateTimeand recurringinterval, with the original Kind preserved.
Remarks
If after is earlier than or equal to dateTime, the method returns
dateTime. Otherwise, it computes the smallest multiple of interval added
to dateTime that occurs strictly after after. When
after falls exactly on an occurrence boundary, that occurrence is excluded and the following
one is returned.
Example:
var start = new DateTime(2025, 7, 7, 9, 0, 0); // 09:00
var interval = TimeSpan.FromHours(1); // every hour
var after = new DateTime(2025, 7, 7, 10, 45, 0); // 10:45
var next = start.NextOccurrence(interval, after); // → 11:00
Exceptions
- ArgumentOutOfRangeException
Thrown if
intervalis less than or equal to Zero.
NextOrSameDateOfWeek(DateTime, DayOfWeek)
Returns a new DateTime representing the next calendar occurrence of the specified
DayOfWeek at or after the given dateTime.
public static DateTime NextOrSameDateOfWeek(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search forward.
dayOfWeekDayOfWeekThe DayOfWeek to locate. For example, Monday returns the next Monday on or after
dateTime.
Returns
- DateTime
An object whose value is set to the next occurrence of
dayOfWeekat or afterdateTime, with the original time-of-day and Kind preserved.
Remarks
If dateTime already falls on the specified dayOfWeek, the result is
dateTime itself. This is the on-or-after counterpart of
NextDateOfWeek(DateTime, DayOfWeek), which always advances by at least one day.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
NextWeekday(DateTime, WeekPattern)
Returns a new DateTime representing the next day after dateTime whose
DayOfWeek is selected in the supplied workingWeek.
public static DateTime NextWeekday(this DateTime dateTime, WeekPattern workingWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search forward.
workingWeekWeekPatternThe working-week pattern that determines which days are considered working days.
Returns
- DateTime
The first calendar day strictly after
dateTimewhose day-of-week is selected inworkingWeek, with the original time-of-day and Kind preserved.
Remarks
The walk is bounded by the seven distinct DayOfWeek values; when workingWeek
has no days selected (Empty) the method will overrun MaxValue
rather than loop indefinitely. Callers must ensure the supplied pattern selects at least one day.
Exceptions
- ArgumentOutOfRangeException
Thrown when
workingWeekis Empty.
NextWeekday(DateTime, WorkingDaysOfWeek)
Returns a new DateTime representing the next calendar weekday after the specified
dateTime, based on the supplied workingWeek pattern.
public static DateTime NextWeekday(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search forward.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
Returns
- DateTime
An object whose value is set to the first calendar day after
dateTimethat is a working day under the specifiedworkingWeekrule, with the original time-of-day and Kind preserved.
Remarks
The method evaluates each successive day until it finds one that is selected as a working day by the specified
rule. The original dateTime is never returned, even if it already falls on a working day.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.
NextWeekday(DateTime, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Returns a new DateTime representing the next calendar weekday after the specified
dateTime, using the supplied workingWeek pattern and an optional custom
provider.
public static DateTime NextWeekday(this DateTime dateTime, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider)
Parameters
dateTimeDateTimeThe starting date and time value from which to search forward.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom. If null, the default behavior for the suppliedworkingWeekapplies.
Returns
- DateTime
An object whose value is set to the first calendar day after
dateTimethat is a working day under the specifiedworkingWeekrule and the logic ofprovider, with the original time-of-day and Kind preserved.
Remarks
The method evaluates each successive day following dateTime until it finds one that is a
working day, either by the supplied workingWeek pattern or by the custom logic of
provider.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.
NthDateOfWeekInMonth(DateTime, DayOfWeek, WeekOrdinal)
Returns a new DateTime representing the specified ordinal occurrence of a
DayOfWeek within the same calendar month and year as the specified dateTime.
public static DateTime NthDateOfWeekInMonth(this DateTime dateTime, DayOfWeek dayOfWeek, WeekOrdinal ordinal)
Parameters
dateTimeDateTimeThe date and time value whose month and year are used to determine the result. The day component is ignored.
dayOfWeekDayOfWeekThe DayOfWeek to locate within the month. For example, Monday returns the nth Monday.
ordinalWeekOrdinalThe ordinal occurrence to return. Valid values are First, Second, Third, Fourth, Fifth, and Last. Fifth is valid only in months where five matching weekdays occur.
Returns
- DateTime
An object whose value is set to midnight (00:00:00) on the requested occurrence of
dayOfWeekwithin the same calendar month and year asdateTime, with the original Kind preserved.
Remarks
For Last, the method returns the final matching dayOfWeek in the
month. For other ordinal values, the method locates the first matching weekday and offsets by a multiple of
seven days to reach the desired ordinal.
The returned value has its time component normalized to midnight (00:00:00), and the original Kind is retained.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration, -or-ordinalis not a defined value of the WeekOrdinal enumeration, -or- the requestedordinaldoes not occur within the month (for example, a fifth Thursday in February).
PreviousDateOfWeek(DateTime, DayOfWeek)
Returns a new DateTime representing the previous calendar occurrence of the specified
DayOfWeek before the given dateTime.
public static DateTime PreviousDateOfWeek(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search backward.
dayOfWeekDayOfWeekThe DayOfWeek to locate. For example, Monday returns the previous Monday.
Returns
- DateTime
An object whose value is set to the previous occurrence of
dayOfWeekprecedingdateTime, with the original time-of-day and Kind preserved.
Remarks
If dateTime already falls on the specified dayOfWeek, the result is
exactly seven days earlier. The method moves backward in time and never returns the original date.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
PreviousOccurrence(DateTime, TimeSpan, DateTime)
Returns a new DateTime representing the previous occurrence of a recurring event that starts at
dateTime and repeats every interval, occurring strictly before the
specified before timestamp.
public static DateTime PreviousOccurrence(this DateTime dateTime, TimeSpan interval, DateTime before)
Parameters
dateTimeDateTimeThe date and time value representing the initial reference point of the recurring event.
intervalTimeSpanThe fixed TimeSpan between successive occurrences. Must be greater than Zero.
beforeDateTimeThe point in time before which the previous occurrence must fall.
Returns
- DateTime
An object whose value is the last occurrence of the event that falls strictly before
before, based on the supplieddateTimeand recurringinterval, with the original Kind preserved.
Remarks
If before is earlier than or equal to dateTime, the method returns the
occurrence immediately prior to dateTime. Otherwise, it computes the largest multiple of
interval added to dateTime that remains strictly less than
before. When before falls exactly on an occurrence boundary, the
occurrence at that boundary is excluded and the preceding one is returned.
Example:
var start = new DateTime(2025, 7, 7, 9, 0, 0); // 09:00
var interval = TimeSpan.FromHours(1); // every hour
before is between two occurrences - returns the occurrence at 10:00
var before1 = new DateTime(2025, 7, 7, 10, 45, 0); // 10:45
var prev1 = start.PreviousOccurrence(interval, before1); // → 10:00
before falls exactly on an occurrence - returns the one before it
var before2 = new DateTime(2025, 7, 7, 11, 0, 0); // 11:00 (on boundary)
var prev2 = start.PreviousOccurrence(interval, before2); // → 10:00
Exceptions
- ArgumentOutOfRangeException
Thrown if
intervalis less than or equal to Zero.
PreviousOrSameDateOfWeek(DateTime, DayOfWeek)
Returns a new DateTime representing the previous calendar occurrence of the specified
DayOfWeek at or before the given dateTime.
public static DateTime PreviousOrSameDateOfWeek(this DateTime dateTime, DayOfWeek dayOfWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search backward.
dayOfWeekDayOfWeekThe DayOfWeek to locate. For example, Monday returns the previous Monday on or before
dateTime.
Returns
- DateTime
An object whose value is set to the previous occurrence of
dayOfWeekat or beforedateTime, with the original time-of-day and Kind preserved.
Remarks
If dateTime already falls on the specified dayOfWeek, the result is
dateTime itself. This is the on-or-before counterpart of
PreviousDateOfWeek(DateTime, DayOfWeek), which always retreats by at least one day.
Exceptions
- ArgumentOutOfRangeException
Thrown if
dayOfWeekis not a defined value of the DayOfWeek enumeration.
PreviousWeekday(DateTime, WeekPattern)
Returns a new DateTime representing the previous day before dateTime whose
DayOfWeek is selected in the supplied workingWeek.
public static DateTime PreviousWeekday(this DateTime dateTime, WeekPattern workingWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search backward.
workingWeekWeekPatternThe working-week pattern that determines which days are considered working days.
Returns
- DateTime
The first calendar day strictly before
dateTimewhose day-of-week is selected inworkingWeek, with the original time-of-day and Kind preserved.
Exceptions
- ArgumentOutOfRangeException
Thrown when
workingWeekis Empty.
PreviousWeekday(DateTime, WorkingDaysOfWeek)
Returns a new DateTime representing the previous calendar weekday before the specified
dateTime, based on the supplied workingWeek pattern.
public static DateTime PreviousWeekday(this DateTime dateTime, WorkingDaysOfWeek workingWeek)
Parameters
dateTimeDateTimeThe starting date and time value from which to search backward.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
Returns
- DateTime
An object whose value is set to the first calendar day before
dateTimethat is a working day under the specifiedworkingWeekrule, with the original time-of-day and Kind preserved.
Remarks
The method evaluates each preceding day until it finds one that is selected as a working day by the specified
rule. The original dateTime is never returned, even if it already falls on a working day.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.
PreviousWeekday(DateTime, WorkingDaysOfWeek, IWeekendDefinitionProvider?)
Returns a new DateTime representing the previous calendar weekday before the specified
dateTime, using the supplied workingWeek pattern and an optional custom
provider.
public static DateTime PreviousWeekday(this DateTime dateTime, WorkingDaysOfWeek workingWeek, IWeekendDefinitionProvider? provider)
Parameters
dateTimeDateTimeThe starting date and time value from which to search backward.
workingWeekWorkingDaysOfWeekThe WorkingDaysOfWeek that determines which days are treated as working days.
providerIWeekendDefinitionProviderAn optional IWeekendDefinitionProvider that supplies custom weekend logic when
workingWeekis Custom. If null, the default behavior for the suppliedworkingWeekapplies.
Returns
- DateTime
An object whose value is set to the first calendar day before
dateTimethat is a working day under the specifiedworkingWeekrule and the logic ofprovider, with the original time-of-day and Kind preserved.
Remarks
The method evaluates each preceding day prior to dateTime until it finds one that is a
working day, either by the supplied workingWeek pattern or by the custom logic of
provider.
Exceptions
- ArgumentOutOfRangeException
Thrown if
workingWeekis not a defined value of the WorkingDaysOfWeek enumeration.
Quarter(DateTime)
Returns the quarter number (1 - 4) of the year for the specified DateTime, using the standard calendar quarter definition.
public static int Quarter(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
- int
An integer between 1 and 4 representing the calendar quarter that contains
dateTime.
Remarks
This overload uses the standard calendar alignment defined by JanuaryToDecember: Q1 = Jan - Mar, Q2 = Apr - Jun, Q3 = Jul - Sep, Q4 = Oct - Dec.
Quarter(DateTime, CalendarQuarterDefinition)
Returns the quarter number (1 - 4) for the specified DateTime, using the supplied calendar quarter definition.
public static int Quarter(this DateTime dateTime, CalendarQuarterDefinition definition)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
definitionCalendarQuarterDefinitionThe CalendarQuarterDefinition that determines how the year is segmented into quarters.
Returns
- int
An integer between 1 and 4 representing the quarter that contains
dateTime.
Remarks
This overload supports both month-aligned and day-aligned quarter definitions. For provider-driven custom calendars (e.g. 4-4-5 retail calendars), use the Quarter(DateTime, IQuarterDefinitionProvider) overload.
Exceptions
- ArgumentOutOfRangeException
Thrown if
definitionis not a defined value of the CalendarQuarterDefinition enumeration.- InvalidOperationException
Thrown if
definitionis Custom; use the provider-based overload instead.
Quarter(DateTime, IQuarterDefinitionProvider)
Returns the quarter number (1 - 4) for the specified DateTime, using a custom IQuarterDefinitionProvider.
public static int Quarter(this DateTime dateTime, IQuarterDefinitionProvider provider)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
providerIQuarterDefinitionProviderThe IQuarterDefinitionProvider that defines custom quarter boundaries. Must not be null.
Returns
- int
An integer between 1 and 4 representing the quarter that contains
dateTime.
Remarks
This overload supports advanced or domain-specific quarter systems by delegating to GetQuarter(DateTime) - for example, 4-4-5 retail calendars or regional fiscal quarters.
Exceptions
- ArgumentNullException
Thrown if
provideris null.- ArgumentOutOfRangeException
Thrown if the value returned by
provideris not in the range 1 - 4.
StartOfDay(DateTime)
Returns a new DateTime representing the start of the calendar day (00:00:00) that contains the
specified dateTime.
public static DateTime StartOfDay(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value whose date is preserved while the time is reset to midnight.
Returns
- DateTime
An object whose value is set to 00:00:00 on the same calendar day as
dateTime, with the original Kind preserved.
Remarks
This method is functionally equivalent to Midnight(DateTime) and to accessing Date. It normalizes the time component to midnight while retaining the date and Kind of the input.
Example:
var dt = new DateTime(2024, 12, 5, 10, 45, 0, DateTimeKind.Utc);
var result = dt.StartOfDay(); // → 2024-12-05 00:00:00 (Kind = Utc)
ToDateOnly(DateTime)
Returns a new DateOnly representing the calendar date of the specified
dateTime, excluding any time-of-day or Kind information.
public static DateOnly ToDateOnly(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to convert.
Returns
Remarks
This method is supported on .NET 6.0 and later. The returned DateOnly is constructed using the Year, Month, and Day components of the input. Any time-of-day component and the Kind property are discarded.
Example:
var dt = new DateTime(2025, 7, 7, 15, 30, 0);
var result = dt.ToDateOnly(); // → 2025-07-07
ToDateTimeOffset(DateTime)
Returns a new DateTimeOffset representing the same moment as the specified
dateTime, with the offset inferred from its Kind.
public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to convert.
Returns
- DateTimeOffset
A DateTimeOffset representing the same point in time as
dateTime, with the offset derived from its Kind.
Remarks
The behavior depends on the Kind of the input:
- Utcapplies a zero offset (UTC).
- Localapplies the system's local time zone offset.
- Unspecifiedtreats the value as local time and applies the system's local offset.
Exceptions
- ArgumentOutOfRangeException
Thrown if the resulting UTC time is outside the supported range of DateTimeOffset.
ToDateTimeOffset(DateTime, TimeSpan)
Returns a new DateTimeOffset representing the same clock time as the specified
dateTime, with the supplied offset applied.
public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime, TimeSpan offset)
Parameters
dateTimeDateTimeThe date and time value to convert.
offsetTimeSpanThe UTC TimeSpan offset to associate with the resulting DateTimeOffset. Must be within the range ±14 hours.
Returns
- DateTimeOffset
A DateTimeOffset with the same local time as
dateTimeand the suppliedoffsetapplied.
Remarks
Use this overload to explicitly associate a non-local offset - for example when dealing with fixed time zones, historical data, or offset-based scheduling.
Exceptions
- ArgumentException
Thrown if
offsetis not within the range ±14 hours, -or-offsetis incompatible with the Kind ofdateTime.- ArgumentOutOfRangeException
Thrown if the resulting UTC time is outside the supported range of DateTimeOffset.
ToIsoString(DateTime)
Returns a string representation of the specified dateTime in ISO 8601 format, using its
Kind to determine the appropriate format suffix.
public static string ToIsoString(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to convert.
Returns
Remarks
Uses the "o" (round-trip) format for Local and
Unspecified, and a custom UTC format ("yyyy-MM-ddTHH:mm:ss.fffffffZ") for
Utc.
ToIsoString(DateTime, bool)
Returns a string representation of the specified dateTime in ISO 8601 format, optionally
omitting fractional seconds.
public static string ToIsoString(this DateTime dateTime, bool includeFractionalSeconds)
Parameters
dateTimeDateTimeThe date and time value to convert.
includeFractionalSecondsboolIndicates whether to include fractional seconds (7 digits) in the output.
Returns
Remarks
Uses the "o" (round-trip) format when includeFractionalSeconds is
true; otherwise uses "yyyy-MM-ddTHH:mm:ss".
ToIsoString(DateTime, DateTimeKind)
Returns a string representation of the specified dateTime in ISO 8601 format, using an
explicit DateTimeKind override.
public static string ToIsoString(this DateTime dateTime, DateTimeKind kind)
Parameters
dateTimeDateTimeThe date and time value to convert.
kindDateTimeKindThe DateTimeKind to apply before formatting.
Returns
- string
A string representation of
dateTimein ISO 8601 format:- Utc - ends with
'Z'; - Local - includes the local time zone offset;
- Unspecified - omits any offset.
- Utc - ends with
Exceptions
- ArgumentOutOfRangeException
Thrown if
kindis not a defined value of the DateTimeKind enumeration.
ToIsoString(DateTime, string, CultureInfo?)
Returns a string representation of the specified dateTime using a custom format and an
optional culture.
public static string ToIsoString(this DateTime dateTime, string format, CultureInfo? culture = null)
Parameters
dateTimeDateTimeThe date and time value to format.
formatstringA valid date-time format string (e.g.
"yyyy-MM-ddTHH:mm:ss"). Must not be null or whitespace.cultureCultureInfoAn optional CultureInfo used for culture-specific formatting. If null, InvariantCulture is used.
Returns
Exceptions
- ArgumentNullException
Thrown if
formatis null.- ArgumentException
Thrown if
formatis empty or whitespace.
ToTimeSpan(DateTime)
Returns a new TimeSpan representing the time-of-day portion of the specified
dateTime.
public static TimeSpan ToTimeSpan(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value from which to extract the time-of-day component.
Returns
- TimeSpan
A TimeSpan value representing the hours, minutes, seconds, and fractional seconds that have elapsed since midnight on the same calendar day as
dateTime.
Remarks
ToUnixTimeMilliseconds(DateTime)
Returns the number of milliseconds that have elapsed between the Unix epoch (1970-01-01T00:00:00Z) and the specified DateTime.
public static long ToUnixTimeMilliseconds(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to convert. The value is first normalized to UTC using ToUniversalTime().
Returns
- long
The total number of milliseconds since the Unix epoch.
Remarks
This method normalizes the input to UTC before computing the elapsed time. Use FromUnixTimeMilliseconds(long) to convert back.
- See Also
ToUnixTimeSeconds(DateTime)
Returns the number of seconds that have elapsed between the Unix epoch (1970-01-01T00:00:00Z) and the specified DateTime.
public static long ToUnixTimeSeconds(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to convert. The value is first normalized to UTC using ToUniversalTime().
Returns
- long
The total number of seconds since the Unix epoch.
Remarks
This method normalizes the input to UTC before computing the elapsed time. Use FromUnixTimeSeconds(long) to convert back.
- See Also
Truncate(DateTime, DateTimeResolution)
Returns a new DateTime obtained by truncating the specified dateTime to the
supplied resolution, with all smaller time components reset to zero.
public static DateTime Truncate(this DateTime dateTime, DateTimeResolution resolution)
Parameters
dateTimeDateTimeThe date and time value to truncate.
resolutionDateTimeResolutionThe DateTimeResolution level to truncate to.
Returns
- DateTime
An object whose value is the result of truncating
dateTimeto the suppliedresolution, with the original Kind preserved.
Remarks
Truncation resets all components smaller than the supplied resolution to their minimum values. For example, truncating to Minute clears seconds and fractional seconds.
The following examples show the result of truncating 2024-04-18T14:37:56.7891234:
| Resolution | Result |
|---|---|
| Year | 2024-01-01T00:00:00.0000000 |
| Month | 2024-04-01T00:00:00.0000000 |
| Day | 2024-04-18T00:00:00.0000000 |
| Hour | 2024-04-18T14:00:00.0000000 |
| Minute | 2024-04-18T14:37:00.0000000 |
| Second | 2024-04-18T14:37:56.0000000 |
| Millisecond | 2024-04-18T14:37:56.7890000 |
| Tick | 2024-04-18T14:37:56.7891234 (unchanged) |
Exceptions
- ArgumentOutOfRangeException
Thrown if
resolutionis not a defined value of the DateTimeResolution enumeration.
WeekOfMonth(DateTime)
Returns the 1-based week number of the month for the specified DateTime, using the CalendarWeekRule and DayOfWeek settings of CurrentCulture.
public static int WeekOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
- int
An integer indicating the week of the month in which
dateTimefalls, starting at1.
Remarks
Week numbering is determined by CurrentCulture, specifically its CalendarWeekRule and FirstDayOfWeek. See WeekOfMonth(DateTime, CalendarWeekRule, DayOfWeek) for the precise semantics of each rule, including the treatment of dates that precede week 1 of their month.
WeekOfMonth(DateTime, CalendarWeekRule, DayOfWeek)
Returns the 1-based week number of the month for the specified DateTime, using the supplied CalendarWeekRule and DayOfWeek as the week-starting day.
public static int WeekOfMonth(this DateTime dateTime, CalendarWeekRule weekRule, DayOfWeek weekStart)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
weekRuleCalendarWeekRuleThe CalendarWeekRule that defines how the first week of the year is identified.
weekStartDayOfWeekThe DayOfWeek on which each week begins.
Returns
- int
An integer indicating the week of the month in which
dateTimefalls, starting at1. Under FirstFullWeek and FirstFourDayWeek, dates that precede week 1 of their month return the week number they carry in the previous month (see remarks).
Remarks
The supplied weekRule determines where week 1 of the month begins, mirroring the semantics
the GetWeekOfYear(DateTime, CalendarWeekRule, DayOfWeek) family applies to years:
FirstDay - week 1 begins on the first day of the month, however short that
partial week is; each subsequent week begins on the next weekStart.
FirstFullWeek - week 1 begins on the first weekStart on or
after the first day of the month. Dates before that boundary belong to the trailing week of the previous month
and return that week's number (for example, 1 March 2024 with a Sunday week start returns 4, the week
number of the week beginning Sunday 25 February).
FirstFourDayWeek - the week containing the first day of the month is week 1 when
at least four of its days fall in that month; otherwise week 1 begins on the following
weekStart and the leading dates resolve to the previous month's trailing week, as for
FirstFullWeek.
The result is therefore never less than 1, but it is not always the week of the date's own month.
Exceptions
- ArgumentOutOfRangeException
Thrown if
weekRuleis not a defined value of the CalendarWeekRule enumeration, -or-weekStartis not a defined value of the DayOfWeek enumeration.
WeekOfMonth(DateTime, CultureInfo?)
Returns the 1-based week number of the month for the specified DateTime, using the calendar settings of the supplied or current culture.
public static int WeekOfMonth(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
cultureCultureInfoAn optional CultureInfo that supplies the CalendarWeekRule and DayOfWeek settings. If null, CurrentCulture is used.
Returns
- int
An integer indicating the week of the month in which
dateTimefalls, starting at1.
Remarks
This overload uses the supplied culture's CalendarWeekRule and FirstDayOfWeek to compute the result. See WeekOfMonth(DateTime, CalendarWeekRule, DayOfWeek) for the precise semantics of each rule, including the treatment of dates that precede week 1 of their month.
WeekOfYear(DateTime)
Returns the 1-based week number of the year that contains the specified DateTime, using the CalendarWeekRule and DayOfWeek settings of CurrentCulture.
public static int WeekOfYear(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
- int
An integer in the range 1 - 53 representing the week of the year that contains
dateTime.
Remarks
Week numbering is determined by CurrentCulture, which may follow different conventions:
- U.S. system: week 1 starts on Sunday and includes January 1.
- ISO 8601: week 1 starts on Monday and includes the first Thursday of the year.
WeekOfYear(DateTime, CalendarWeekRule, DayOfWeek)
Returns the 1-based week number of the year that contains the specified DateTime, using the supplied CalendarWeekRule and DayOfWeek as the week-starting day.
public static int WeekOfYear(this DateTime dateTime, CalendarWeekRule weekRule, DayOfWeek weekStart)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
weekRuleCalendarWeekRuleThe CalendarWeekRule that defines how the first week of the year is identified.
weekStartDayOfWeekThe DayOfWeek on which each week begins.
Returns
- int
An integer in the range 1 - 53 representing the week of the year that contains
dateTime.
Remarks
This overload enables custom calendar logic such as ISO 8601 (FirstFourDayWeek, Monday) or localized U.S./European systems.
Exceptions
- ArgumentOutOfRangeException
Thrown if
weekRuleis not a defined value of the CalendarWeekRule enumeration, -or-weekStartis not a defined value of the DayOfWeek enumeration.
WeekOfYear(DateTime, CultureInfo?)
Returns the 1-based week number of the year that contains the specified DateTime, using the calendar rules of the supplied or current culture.
public static int WeekOfYear(this DateTime dateTime, CultureInfo? culture)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
cultureCultureInfoAn optional CultureInfo that supplies the CalendarWeekRule and DayOfWeek settings. If null, CurrentCulture is used.
Returns
- int
An integer in the range 1 - 53 representing the week of the year that contains
dateTime.
Remarks
This overload allows culture-specific calculation of week numbers (e.g. for Gregorian or ISO 8601 calendars).
WeekOrdinalOfMonth(DateTime)
Returns the WeekOrdinal represented by the specified DateTime, indicating the ordinal occurrence of its DayOfWeek within the month.
public static WeekOrdinal WeekOrdinalOfMonth(this DateTime dateTime)
Parameters
dateTimeDateTimeThe date and time value to evaluate.
Returns
- WeekOrdinal
A WeekOrdinal value indicating which occurrence of the weekday
dateTimerepresents within its calendar month.
Remarks
The result is calculated by counting how many full seven-day intervals have passed since the start of the month, based on Day. For example, the 1st through 7th of the month yield First, while the 8th through 14th yield Second, and so on.
Fifth is only returned when a month contains five occurrences of the given DayOfWeek.
Exceptions
- ArgumentOutOfRangeException
Thrown if the calculated ordinal does not correspond to a defined value of the WeekOrdinal enumeration.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |