views:

127

answers:

4

Hi,

I want to write some sort of dictionary that would accept current time and return what user-define time period it is. As time-preiod I mean user-defined names for time period that are read from file. For example

8:00-9:00 - breakfast time 9:00-12:00 - work time 12:00-13:00 - lunch time

etc...

Currently I have a function is base on if-else if statements

// C# syntax omitted for simplicity
TimePeriod GetCurrentTimePeriod(DateTime t)
{
 if(t < 8.00)
 {
  return TimePeriod.Sleep;
 }
 else if(t < 9.00)
 { 
   ...
 }
}

I am not happy with this straight solution. I would prefer use some sort of "dictionary" instead.

PS. Changed the word TimeZone to TimePeriod to avoid confusion with System.TimeZone class.

+1  A: 

Seems like a good solution to me as written. Alternatively, you could design your own range-based map.

Pavel Radzivilovsky
+3  A: 

If you need to make those "periods of time" dynamically adjustable, I suggest building up a simple List of a record containing start time, end time, and description and simply query that list with LINQ. Since the number of items in that list is probably likely to be very small, linear search does the job and it isn't worth it to bother using binary search or more advanced data structures like segment trees:

class PeriodOfTime { 
   public DateTime StartTime {get; set;}
   public DateTime EndTime {get; set;}
   public string Description {get; set;} // Use your own enum instead
}
// ... 
List<PeriodOfTime> periods = new List<PeriodOfTime>();

var timeToQuery = DateTime.Now.TimeOfDay;
var period = periods.FirstOrDefault(p => timeToQuery >= p.StartTime &&
                                         timeToQuery <= p.EndTime);
Mehrdad Afshari
+1  A: 

You have not to use TimeZone class because you will get different time in specific time zone.

You can use this class for time converting, e.g.

TimeZone localZone = TimeZone.CurrentTimeZone;
DateTime baseUTC = new DateTime(2010, 1, 1);
DateTime localTime = localZone.ToLocalTime(baseUTC);
TimeSpan localOffset = localZone.GetUtcOffset(localTime);

You may use simple check as answer to your question:

if (youTime >= 8.00 && youTime <= 9.00)
 return YourTypes.Breakfast; 
else if (youTime > 9.00 && youTime <= 12.00)
 return YourTypes.WorkTime;
else
 // etc.
sashaeve
The question is not about time zones at all. The use of the name "time zone" is totally confusing, as pointed out in comments by Jon.
Mehrdad Afshari
I understand the question and try to explain this misunderstood in my answer.
sashaeve
+3  A: 

This question was asked a couple of days ago. See the answer here for some ideas of how to proceed.

http://stackoverflow.com/questions/2147505/a-dictionary-object-that-uses-ranges-of-values-for-keys

Eric Lippert
All right, so it is interval trees. Will read about. AlthoughI agree with my task with quire a few items simple linear job will do the job perfectly.
Captain Comic