Click here to Skip to main content
15,881,828 members
Articles / Programming Languages / C#

Time is of the essence

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
6 Jul 2009CPOL 19.3K   95   17   2
DateTime helper methods.

Introduction

While working in different projects, I encountered frustrating problems related to date and time programming. So I wrote a few classes that helped me tackle those problems.

The code

Here is my static helper class:

C#
public static DayOfWeek GetLastDayOfWeek(CultureInfo culture)
public static DateTime GetFirstDateOfWeek(DateTime dateTime, CultureInfo culture)
public static DateTime GetLastDateOfWeek(DateTime dateTime, CultureInfo culture)
public static DateTime GetLastDateOfMonth(int year, int month)
public static DateTime GetLastDateOfYear(int year)
public static int GetWeeksInYear(int year, CultureInfo culture)
public static int GetRemainingDaysInWeek(DateTime dateTime, CultureInfo culture)
public static int GetWeekNumber(DateTime dateTime, CultureInfo culture)
public static bool AreTimePeriodsIntersecting(TimePeriod tp1, TimePeriod tp2)
public static bool IsDateInPeriod(DateTime dateTime, TimePeriod timePeriod)

The TimeDifference class receives a start date and an end date, and returns the difference in Years, Months, Weeks, Days, Hours, Minutes, Seconds, and Miliseconds between them in two modes.

Let's take, for example, two dates: 06/26/2009 and 05/02/2013.

  • First difference mode (time-units independence): 4 years, or (more accurately) 47 months, or (more accurately) 200 weeks, or (more accurately) 1406 days.
  • Second difference mode (time-units dependence): 3 years and 10 months and 6 days.

Hope it will be of great help to someone, and please report any errors or suggestions.

NB: TimeZone and Daylight Savings Time are not taken into account.

License

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


Written By
Software Developer (Senior)
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGetRemainingDaysInWeek Pin
Doncp14-Jul-09 13:41
Doncp14-Jul-09 13:41 
GeneralWeekNumber Pin
Jiaozi6-Jul-09 21:19
Jiaozi6-Jul-09 21:19 

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

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