Correctly handling opening times with NodaTime - c#

I'm currently writing a fairly simple app handling opening/closing times of businesses and running into serious difficulties trying to figure out how to properly store the info.
Most of our critical functionality is heavily dependent on getting times absolutely perfect, so obviously I want to get things done the best way possible to start off with!
Additionally, the data will be inputted by users, so if the underlying representation is slightly more complex (e.g. using TimeSpans to account for opening past midnight), this needs to be invisible to the user.
I need to store firstly, the business's opening hours, by day of week, with a timezone associated with them, e.g:
- M: 1000 - 2330
- T: 1000 - 0030
- W: 1900 - 0300
- Th: 2000 - 0300
- F: 2000 - 0800
- Sa: 1000 - 0500
- Su: 1000 - 2300
I'm currently thinking that the best way to store this is using a class like this:
public class OpeningHours
{
ZonedDateTime OpeningTime { get; set; }
Period durationOpen { get; set; }
// TODO: add a method to calculate ClosingTime as a ZonedDateTime
}
However, there's 2 main complications here:
I don't want to store the Year, Month, or Date part of the ZonedDateTime - I just care about the DayOfWeek.
Sure, I could just store each value as the first Monday/Tuesday etc after Jan 1 1970, but this seems hacky and pretty much plain wrong - as the author of NodaTime, very correctly, explains here when talking about the limitations of the BCL DateTime implementation. I also have a feeling this would probably end up with weird quirky bugs if later on we try and do any arithmetic with the dates.
The user is going to have to input the ClosingTime anyway. Client side I suppose I could do something simple like always assume the ClosingTime is the next day if it's before the OpeningTime, but again, it's not perfect, and also doesn't account for places that might be open for more than 24 hours (e.g. supermarkets)
Another thing I've considered is using a table with hours/days and letting people highlight the hours of the week to pick opening times, but you still run into the same problem with only wanting to store the DayOfWeek part of the OpeningTime.
Any suggestions would be appreciated, spending the last 6 hours reading about the hilariously silly ways we humans represent time has burnt me out a bit!

I would strongly consider using LocalTime instead of ZonedDateTime, for a couple of reasons:
You're not trying to represent a single instant in time; these are naturally recurring patterns (there's no associated date)
You're not trying to cope with the situation where the store is in different time zones for different opening hours; you probably want to associate a time zone with each store once, and then you can apply that time zone whenever you want
So I would have something like this (showing just the data members; how you sort out the behaviour is a separate matter):
public class StoreOpeningPeriod
{
IsoDayOfWeek openingDayOfWeek;
LocalTime openingTime;
LocalTime closingTime;
}
Note that this exactly follows your original data as you've shown it, which is always a good sign - you're neither adding nor losing information, and it's presumably in a convenient form.
If the closing time is earlier than the opening time, it's assumed that this crossed midnight - you might want to add a confirmation box for the user if this is relatively uncommon, but it's certainly easy to spot and handle in code.

Related

Can DateTime represent a date before Christ / before our time? or How is this managed?

So, I noticed DateTime.MinValue defaults to 01-01-0001 (dd-MM-yyyy), so for example let's say we have a museum database/class object whatever, how do you store an object that is from 10,000 BC or how about dinosaur bones that are from millions of years prior to today?
Can it be a signed value? like, the year "-10000" represents BC?
or we would need to rely on strings and be unable to natively work with dates prior to year 1?
I checked this question out that asks for year zero, but it doesn't have any helpful insights, other than apparently not everyone knows there is no such thing as year zero. how make a datetime object in year 0 with python
No, DateTime doesn't handle anything before 1CE.
My Noda Time project does support BCE dates, but still limited to about 9998 BCE as the earliest it can handle.
Once you're talking about prehistoric times, you probably have a different set of use cases from normal date/time types anyway - so just extending the range of the existing types may well not help you much. (As an example, quite often ancient history deals with relative dates: "I know battle X took place 3 years into the reign of king Y, but I don't know exactly when either of them happened.") I'd suggest you think about what your actual use cases are, and what you need to do with the date/time information. Then you can look into whether existing libraries meet your needs, or whether you need to write your own abstractions.
After digging around, I've found that other than creating one's own types, there is no easy native solutions to this specific use case for dates, so I want to propose my solution in case its of use to anyone. Just add a column that will have a sign, a - and a + (or a 0 and 1 I guess with a boolean type). Dates with + are AC and dates with - are BC. On your code or otherwise you'll have to handle the sign. Its simple and requires no extra libraries or technologies.
Since dates have no zeros the sign should not create interference, and just minding negative dates move in reverse order in your logic will solve any issues with that. However this solution only works for dates up to year 9999, so in order to be able to handle even farther away dates, a more complex sistem would have to be programmed. like handling each part of a date in a separate column so it can cover as many years as int or double can do numbers.
However, I do think positive dates from the year 3000 up to the year 9999 will hardly ever be used, much less towards millions of years into the future. But maybe it will be of use for fan proyect databases for sci-fi universes like 40K or SW or ST.

How do I accurately represent a Date Range in NodaTime?

Goals
I have a list of LocalDate items that represent sets of start dates and end dates.
I would like to be able to store date ranges, so that I can perform operations on them as a set of overlapping or distinct ranges, etc.
Questions
Does NodaTime provide some sort of DateRange construct that I've missed in the docs?
Am I thinking about this wrong? Is there a more natural / preferred way to accomplish this that NodaTime already allows for?
Am I setting myself up for trouble by attempting to think about a date range using a LocalDate for a start and an end date?
I'm completely new to NodaTime and assuming that this is a conceptual misunderstanding on my part.
Update: I noticed a similar question on the subject from 2009, but that seems to refer to another utilies class; I'm assuming that since then NodaTime may have evolved to accomodate this situation.
Noda Time provides an Interval type for a range of Instant values, but it doesn't provide range types for the other types. Part of the reason for this is the nuance of how ranges are used for different types.
If I give you a range of instants, it is always treated as a half open interval. The start value is included, but the end value is excluded. Humans do this naturally any time we provide a time value, such as when I say an event runs from 1:00 to 2:00, clearly I mean that the event is over at 2:00, so 2:00 is excluded.
But with whole calendar date ranges, typically the end dates are inclusive. To represent the entire month of January (as a range of LocalDate values), I would probably say Jan 1st through Jan 31st, and I am including the last day in its entirety.
We could probably add some additional range types to enforce these things, but we would need to think about how much value there is in having them in the API when you could probably just create them as needed. I'm not saying I'm for or against it either way, but that's probably something to be debated on the Noda Time user group.
To answer your specific questions:
No, there is no predefined range class for local dates.
The only other thing to consider is that calendar math is usually done via the Period class. For example, to determine how many days there are between two calendar dates:
LocalDate ld1 = new LocalDate(2012, 1, 1);
LocalDate ld2 = new LocalDate(2013, 12, 25);
Period period = Period.Between(ld1, ld2, PeriodUnits.Days);
long days = period.Days;
No, there's nothing wrong with creating a range class of local dates, there just might not be a whole lot of advantage. You may do just as well by having two properties, StartDate and EndDate, on your own classes. Just be careful about the inclusiveness of the end dates, vs the exclusiveness you'd see with an interval or time range.
And lastly, you said:
... so that I can perform operations on them as a set of overlapping or distinct ranges, etc.
You're probably looking for operations like intersection, union, calculating gaps, sorting, etc. These and more are defined by the Time Period Library, but Noda Time doesn't currently have anything like that. If one was to create it, it should probably be in a companion library ("NodaTime.Ranges", perhaps?). Likely it wouldn't be desired to pull it into the core, but you never know...
If you do end up using that Time Period Library, please make sure you recognize that it works with DateTime only, and is completely oblivious to DateTimeKind. So in order to be productive with it, you should probably make sure you are only working with UTC values, or "unspecified" calendar dates, and try not to ask it things like "how many hours are in a day" because it will get it wrong for days with daylight saving time transitions.

.Net - Time of the day

I am working on an application that needs to set rules for periods of time. The company has different branches, each branch can set its own rules (i.e a branch starts work at 8.30 am, ends work at 17.30 pm, with 30 minutes pause for lunch; another branch start at 9.00, ends at 19.00 with 1 hour pause...)
So I need to define a class (let's call it WorkingDayDefinition for the moment) where start and end are not actually a DateTime, because they are not referred to any specific day in particular.
At the moment the only option I see in C# is using Timespan for setting a duration from the beginning of the day, so that 8.30 pm would be TimeSpan(8,30,0) to be added to the Day part of whichever day.
Is this a best practice in C#?
I searched for third parties libraries that could help me, but so far my best bet is this one:
http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
that is not strictly what I need
You could use Noda Time. It provides a LocalTime (see here):
LocalTime is an immutable struct representing a time of day, with no reference to a particular calendar, time zone or date.
For 8.30 you would do something like:
LocalTime openingAt = new LocalTime(8, 30);
To me TimeSpam seems very suitable for what you want. It holds an interval of time, sometimes between two events, but in your case between the start of the day and the time you start/finish work. There is no reason I can think of not to use it just because the name might suggest this wasn't the original intention of the class. Plus it already integrates well with DateTimes for any time calculations you need to do later on down the road.

Add 1 week to current date

I've got something like this DateTime.Now.ToString("dd.MM.yy"); In my code, And I need to add 1 week to it, like 5.4.2012 to become 12.4.2012 I tried to convert it to int and then add it up, but there is a problem when it's up to 30.
Can you tell me some clever way how to do it?
You want to leave it as a DateTime until you are ready to convert it to a string.
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
First, always keep the data in it's native type until you are ready to either display it or serialize it (for example, to JSON or to save in a file). You wouldn't convert two int variables to strings before adding or multiplying them, so don't do it with dates either.
Staying in the native type has a few advantages, such as storing the DateTime internally as 8 bytes, which is smaller than most of the string formats. But the biggest advantage is that the .NET Framework gives you a bunch of built in methods for performing date and time calculations, as well as parsing datetime values from a source string. The full list can be found here.
So your answer becomes:
Get the current timestamp from DateTime.Now. Use DateTime.Now.Date if you'd rather use midnight than the current time.
Use AddDays(7) to calculate one week later. Note that this method automatically takes into account rolling over to the next month or year, if applicable. Leap days are also factored in for you.
Convert the result to a string using your desired format
// Current local server time + 7 days
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
// Midnight + 7 days
DateTime.Now.Date.AddDays(7).ToString("dd.MM.yy");
And there are plenty of other methods in the framework to help with:
Internationalization
UTC and timezones (though you might want to check out NodaTime for more advanced applications)
Operator overloading for some basic math calcs
The TimeSpan class for working with time intervals
Any reason you can't use the AddDays method as in
DateTime.Now.AddDays(7)

How to design Date-of-Birth in DB and ORM for mix of known and unknown date parts

Note up front, my question turns out to be similar to SO question 1668172.
This is a design question that surely must have popped up for others before, yet I couldn't find an answer that fits my situation. I want to record date-of-birth in my application, with several 'levels' of information:
NULL value, i.e. DoB is unkown
1950-??-?? Only the DoB year value is known, date/month aren't
????-11-23 Just a month, day, or combination of the two, but without a year
1950-11-23 Full DoB is known
The technologies I'm using for my app are as follows:
Asp.NET 4 (C#), probably with MVC
Some ORM solution, probably Linq-to-sql or NHibernate's
MSSQL Server 2008, at first just Express edition
Possibilities for the SQL bit that crossed my mind so far:
1) Use one nullable varchar column e.g. 1950-11-23, and replace unkowns with 'X's, e.g. XXXX-11-23 or 1950-XX-XX
2) Use three nullable int columns e.g. 1950, 11, and 23
3) Use an INT column for year, plus a datetime column for full known DoBs
For the C# end of this problem I merely got to these two options:
A) Use a string property to represent DoB, convert only for view purposes.
B) Use a custom(?) struct or class for DoB with three nullable integers
C) Use a nullable DateTime alongside a nullable integer for year
The solutions seem to form matched pairs at 1A, 2B or 3C. Of course 1A isn't a nice solution, but it does set a baseline.
Any tips and links are highly appreciated. Well, if they're related, anyhow :)
Edit, about the answers: I marked one answer as accepted, because I think it will work for me. It's worth looking at the other answers too though, if you've stumbled here with the same question.
The SQL Side
My latest idea on this subject is to use a range for dates that are uncertain or can have different specificity. Given two columns:
DobFromDate (inclusive)
DobToDate (exclusive)
Here's how it would work with your scenarios:
Specificity DobFromDate DobToDate
----------- ----------- ----------
YMD 2006-05-05 2006-05-06
YM 2006-05-01 2006-06-01
Y 2006-01-01 2007-01-01
Unknown 0000-01-01 9999-12-31
-> MD, M, D not supported with this scheme
Note that there's no reason this couldn't be carried all the way to hour, minute, second, millisecond, and so on.
Then when querying for people born on a specific day:
DECLARE #BornOnDay date = '2006-05-16'
-- Include lower specificity:
SELECT *
FROM TheTable
WHERE
DobFromDate <= #BornOnDay
AND #BornOnDay < DobToDate;
-- Exclude lower specificity:
SELECT *
FROM TheTable
WHERE
DobFromDate = #BornOnDay
AND DobToDate = DateAdd(Day, 1, #BornOnDay);
This to me has the best mix of maintainability, ease of use, and expressive power. It won't handle loss of precision in the more significant values (e.g., you know the month and day but not the year) but if that can be worked around then I think it is a winner.
If you will ever be querying by date, then in general the better solutions (in my mind) are going to be those that preserve the items as dates on the server in some fashion.
Also, note that if you're looking for a date range rather than a single day, with my solution you still only need two conditions, not four:
DECLARE
#FromBornOnDay date = '2006-05-16',
#ToBornOnDay date = '2006-05-23';
-- Include lower specificity:
SELECT *
FROM TheTable
WHERE
DobFromDate < #ToBornOnDay
AND #FromBornOnDay < DobToDate;
The C# Side
I would use a custom class with all the methods needed to do appropriate date math and date comparisons on it. You know the business requirements for how you will use dates that are unknown, and can encode the logic within the class. If you need something before a certain date, will you use only known or unknown items? What will ToString() return? These are things, in my mind, best solved with a class.
I like the idea of 3 int nullable columns and a struct of 3 nullable int in C#.
it does take some effort in db handling but you can avoid parsing around strings and you can also query with SQL directly by year or year and month and so on...
Whatever you do is going to be messy DB wise. For consumers of these kind of dates, I would write a special class/struct which encapsulates what sort of date it is (I'd probably call it something like PartialDate), to make it easier to deal with for consumers- much like Martin Fowler advocates a Money Class.
If you expose a DateTime directly in C#, this could lead to confusion if you had a "date" of ????-11-23 and you wanted to determine if the customer was over 18 for example- how would you default the date, how would the consumer know that part of the date was invalid etc...
The added benefit of having a PartialDate is it will allow other people reading your code to quickly realise that they are not normal, complete dates and should not be treated as such!
Edit
Thinking about the Partial data concept some more, I decided to Google. I found that There is the concept of Partial on Joda time and an interesting PDF on the topic, which may or may not be useful to you.
Interesting problem...
I like solution 2B over solution 3C because with 3C, it wouldn't be normalized... when you update one of the ints, you'd have to update the DateTime as well or you would be out of sync.
However, when you read the data into your C# end, I'd have a property that would roll up all the ints into a string formatted like you have in solution 1 so that it could easily be displayed.
I'm curious what type of reporting you'll need to do on this data... or if you'll simply be storing and retrieving it from the database.
I would not worry to much about how to store the date, I would still store the date within a datetime field, BUT, if knowing if some part of the date was not populated, I would have flags for each section of the date that is not valid, so your schema would be:
DBODate as Date
DayIsSet as Bit
MonthIsSet as Bit
YearIsSet as Bit.
That way you can still implement all the valid date comparisons, and still know the precision of the date you are working on. (as for the date, I would always default to the missing portion as the min of that value: IE Month default is January, day is the first, year is 1900 or something).
Obviously, all of the solutions mentioned above do represent some kind of compromise.
Therefore, I would recommend to think carefully which of the 'levels' is the most likely one and optimize for that. Afterwards go for proper exception handling for the other rare cases.
I don't know whether reporting is an issue for you right now or may be later, but you might consider that as third dimension apart from the DB / C# issues.

Categories