Suppose that I want to build a notification system in which users can configure what time during the week they will receive notification.

So I might want to get notifications on Monday 10 am - 2 pm and Thursday 8 pm - Friday 8 am

something like that. But would the object be like?

I am thinking

class TimePeriod {
    DateTime start;
    int durationInMinutes;

This is simple, but this does not consider timezones(system time vs user time)/daylight savings (US stuff)/etc. what would be a good pattern for such "duration" objects?


Good pattern here is to always convert to and from UTC on some (and always same) border. For example, you can store datetimes in UTC, you can do most of the interval logic in UTC, and the only time you need to convert to is when you display or input values (eg, in the web browser).

Well, there may be exceptions to this rule. If your domain model operates with concepts like for instance "night" and "day", then in the model itself you need knowledge about user's timezone and in the functions which deal with timezone-specific calculations use that knowledge. You need to carefully discover all cases where timezone can influence domain logic decisions.

Another approach is to always use timezone-aware datetimes. However, it may be more difficult as it depends on the capabilities of the libraries you are using and also whether part of your system use naive datetimes (that is, ignoring timezones). Mixing these can be dangerous.

Duration is mentioned in the question, but I can hardly see how it can influence timezone problem. Also, when summer time changes to winter time, there are two hours, which are exactly the same if we do not know UTC or daylight saving flag. So, storing duration may be a bit better way to avoid ambiguity at that particular hour of the year if for some reason you cant do it all in UTC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.