Extension Methods in C#





5.00/5 (6 votes)
You inspired me to contribute the DateTime extensions methods that I use in my programs. (But use at your own risk!). Thank you./// /// Date and Time Manager class./// public static class DateMan{ /// /// Returns the age in years for the given DOB...
You inspired me to contribute the
DateTime
extensions methods that I use in my programs. (But use at your own risk!). Thank you.
/// <summary>
/// Date and Time Manager class.
/// </summary>
public static class DateMan
{
/// <summary>
/// Returns the age in years for the given DOB
/// </summary>
public static int Age(this DateTime dob)
{
return (int)((DateTime.Now - dob).Days / 365.25);
}
/// <summary>
/// Returns true if given date time falls in the morning (AM).
/// </summary>
public static bool IsMorning(this DateTime time)
{
return time.TimeOfDay < new DateTime(2000, 1, 1, 12, 0, 0).TimeOfDay;
}
/// <summary>
/// Returns true if given date time falls in the afternoon (PM).
/// </summary>
public static bool IsAfternoon(this DateTime time)
{
return time.TimeOfDay >= new DateTime(2000, 1, 1, 12, 0, 0).TimeOfDay;
}
/// <summary>
/// Returns the start of the next hour following the given time.
/// </summary>
public static DateTime StartOfNextHour(this DateTime time)
{
DateTime result = time.AddHours(1).AddMinutes(-time.Minute).AddSeconds(-time.Second);
return result;
}
/// <summary>
/// Returns the start of the day following the given time.
/// </summary>
public static DateTime StartOfNextDay(this DateTime time)
{
DateTime result = time.AddDays(1);
return result.Date;
}
/// <summary>
/// Returns the start of the current week.
/// </summary>
public static DateTime StartOfThisWeek(this DateTime time)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
// Calculate difference between specified date days of week and first day of week
int Days = time.DayOfWeek - dfi.FirstDayOfWeek;
// Add day difference to number of days in week then divide sum with days in week, reminder is number of days we need to subtract
Days = (7 + Days) % 7;
// Subtract difference of days from specified date
return time.AddDays(-Days);
}
/// <summary>
/// Returns the start of the week following the given time.
/// </summary>
public static DateTime StartOfNextWeek(this DateTime time)
{
return time.StartOfThisWeek().AddDays(7);
}
/// <summary>
/// Returns the start of the month for the month following the given time.
/// </summary>
public static DateTime StartOfNextMonth(this DateTime time)
{
DateTime result = time.AddMonths(1);
return new DateTime(result.Year, result.Month, 1);
}
/// <summary>
/// Returns the start of the month for the current month.
/// </summary>
public static DateTime StartOfThisMonth(this DateTime time)
{
return new DateTime(time.Year, time.Month, 1);
}
/// <summary>
/// Returns the end of the month for the current month.
/// </summary>
public static DateTime EndOfThisMonth(this DateTime time)
{
DateTime result = time.AddMonths(1);
return new DateTime(result.Year, result.Month, 1).AddDays(-1);
}
/// <summary>
/// Returns the start of the year for the year following the given time.
/// </summary>
public static DateTime StartOfNextYear(this DateTime time)
{
DateTime result = time.AddYears(1);
return new DateTime(result.Year, 1, 1);
}
/// <summary>
/// Assumes the given string is the description for a month.
/// Returns the integer value representing that month.
/// </summary>
/// <remarks>
/// A 3 letter representation is enough, whole name not needed (though accepted).
/// </remarks>
public static int GetMonthByDescription(this string month)
{
if (month.IsInteger())
{
return int.Parse(month);
}
if (month.Trim().Length <= 2)
{
throw new Exception("Input not a valid month representation.");
}
int result = 0;
switch (month.Left(3).ToLower())
{
case "jan":
result = 1;
break;
case "feb":
result = 2;
break;
case "mar":
result = 3;
break;
case "apr":
result = 4;
break;
case "may":
result = 5;
break;
case "jun":
result = 6;
break;
case "jul":
result = 7;
break;
case "aug":
result = 8;
break;
case "sep":
result = 9;
break;
case "oct":
result = 10;
break;
case "nov":
result = 11;
break;
case "dec":
result = 12;
break;
}
return result;
}
/// <summary>
/// Parses a millisecond value into Days, Hours, Minutes, Seconds and Milliseconds.
/// </summary>
public static void MiliSecParse(int inputMiliSecs, out int days, out int hours, out int minutes, out int seconds, out int miliSeconds)
{
TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, inputMiliSecs);
MiliSecParse(timeSpan, out days, out hours, out minutes, out seconds, out miliSeconds);
}
/// <summary>
/// Parses a millisecond value into Days, Hours, Minutes, Seconds and Milliseconds.
/// </summary>
public static void MiliSecParse(double inputMiliSecs, out int days, out int hours, out int minutes, out int seconds, out int miliSeconds)
{
TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)inputMiliSecs);
MiliSecParse(timeSpan, out days, out hours, out minutes, out seconds, out miliSeconds);
}
/// <summary>
/// Parses a millisecond value into Days, Hours, Minutes, Seconds and Milliseconds.
/// </summary>
public static void MiliSecParse(TimeSpan timeSpan, out int days, out int hours, out int minutes, out int seconds, out int miliSeconds)
{
days = timeSpan.Days;
hours = timeSpan.Hours;
minutes = timeSpan.Minutes;
seconds = timeSpan.Seconds;
miliSeconds = timeSpan.Milliseconds;
}
/// <summary>
/// Returns the number of days in the month of the given date.
/// </summary>
public static int DaysInMonth(this DateTime date)
{
int result = 31;
switch (date.Month)
{
case 2:
result = date.IsLeapYear() ? 29 : 28;
break;
case 4:
result = 30;
break;
case 6:
result = 30;
break;
case 9:
result = 30;
break;
case 11:
result = 30;
break;
}
return result;
}
/// <summary>
/// Returns true if the given date falls in a leap year.
/// </summary>
public static bool IsLeapYear(this DateTime date)
{
int year = date.Year;
return ((year.IsMultipleOf(4) && !year.IsMultipleOf(100)) || year.IsMultipleOf(400));
}
/// <summary>
/// Returns PC time (without daylight savings)
/// </summary>
public static DateTime GetPCTimeNoDaylightSaving()
{
DateTime result = DateTime.Now;
TimeZone timeZone = TimeZone.CurrentTimeZone;
if (timeZone.IsDaylightSavingTime(result))
{
DaylightTime daylightTime = timeZone.GetDaylightChanges(result.Year);
result -= daylightTime.Delta;
}
return result;
}
/// <summary>
/// Returns true if the system's time zone is now experiencing a period of
/// Daylight Savings adjustment. e.g. one hour added
/// </summary>
public static bool IsDaylightSavingTime()
{
return TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now);
}
/// <summary>
/// Returns true if the system's time zone is in a period of
/// Daylight Savings adjustment for the given date. e.g. one hour added
/// </summary>
public static bool IsDaylightSavingTime(DateTime date)
{
return TimeZone.CurrentTimeZone.IsDaylightSavingTime(date);
}
/// <summary>
/// Returns the quarter of the year within which the given date falls:
/// Jan, Feb, Mar = 1
/// ...
/// Oct, Nov, Dec = 4
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static int Quarter(this DateTime date)
{
return (date.Month + 2) / 3;
}
}