Click here to Skip to main content
11,495,524 members (65,518 online)
Click here to Skip to main content

Tagged as

Extension Methods in C#

, 12 Apr 2011 CPOL 4.2K 4
Rate this:
Please Sign up or sign in to vote.
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;
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Kamran Behzad
Software Developer Snowy Hydro Ltd
Australia Australia
I am a .NET C# developer with an engineering background. I have been living and working in Sydney, Australia since 1993.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Edo Tzumer22-Apr-13 23:59
professionalEdo Tzumer22-Apr-13 23:59 
GeneralNice, but your code references some int extension methods I ... Pin
cjb11018-Apr-11 0:34
membercjb11018-Apr-11 0:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 12 Apr 2011
Article Copyright 2011 by Kamran Behzad
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid