Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best class to represent a time

I'm working on timetabling application and I have a class: called ClassOption representing a possible time to have a class. with fields(/properties): Day, StartTime, EndTime, and Weeks.

Now Day is easy it's type is DayOfWeek

Weeks is going to require me to make a custom class because it is represented by the universities own in-semester weeks notation or in a calendar week, but basically will come down to a set of integers, eventually.

But what calls should I use for StartTime and EndTime. They are a time, but without any Date information. DateTime seems like a reasonable choice, but they could be on any date. (/many dates) By business logic they are both on the hour, but that doesn't really matter

like image 415
Lyndon White Avatar asked Jun 08 '26 05:06

Lyndon White


2 Answers

If you're happy to use a third party library which isn't quite at v1 yet, I'd like to plug Noda Time. You'd use the LocalTime struct.

If you're stuck with the base class library, you might want to use TimeSpan, or you could stick with DateTime. Obviously I think that LocalTime would be a more elegant solution though :)

Oh, and if you do use Noda Time, please let us know if you have any feature requests or comments...

like image 185
Jon Skeet Avatar answered Jun 10 '26 17:06

Jon Skeet


You can use the DateDiff class of the Time Period Library for .NET to represent a time period:

// ----------------------------------------------------------------------
public void DateDiffSample()
{
  DateTime date1 = new DateTime( 2009, 11, 8, 7, 13, 59 );
  Console.WriteLine( "Date1: {0}", date1 );
  // > Date1: 08.11.2009 07:13:59
  DateTime date2 = new DateTime( 2011, 3, 20, 19, 55, 28 );
  Console.WriteLine( "Date2: {0}", date2 );
  // > Date2: 20.03.2011 19:55:28

  DateDiff dateDiff = new DateDiff( date1, date2 );

  // description
  Console.WriteLine( "DateDiff.GetDescription(1): {0}", dateDiff.GetDescription( 1 ) );
  // > DateDiff.GetDescription(1): 1 Year
  Console.WriteLine( "DateDiff.GetDescription(2): {0}", dateDiff.GetDescription( 2 ) );
  // > DateDiff.GetDescription(2): 1 Year 4 Months
  Console.WriteLine( "DateDiff.GetDescription(3): {0}", dateDiff.GetDescription( 3 ) );
  // > DateDiff.GetDescription(3): 1 Year 4 Months 12 Days
  Console.WriteLine( "DateDiff.GetDescription(4): {0}", dateDiff.GetDescription( 4 ) );
  // > DateDiff.GetDescription(4): 1 Year 4 Months 12 Days 12 Hours
  Console.WriteLine( "DateDiff.GetDescription(5): {0}", dateDiff.GetDescription( 5 ) );
  // > DateDiff.GetDescription(5): 1 Year 4 Months 12 Days 12 Hours 41 Mins
  Console.WriteLine( "DateDiff.GetDescription(6): {0}", dateDiff.GetDescription( 6 ) );
  // > DateDiff.GetDescription(6): 1 Year 4 Months 12 Days 12 Hours 41 Mins 29 Secs
} // DateDiffSample

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!