Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing Time (not date and time) in C#

Tags:

c#

datetime

time

I'm developing an app that requires the notion of opening times (A bit like a shop)

How best to represent these? They will be persisted in a DB later...

So far I have the following class:

public class OpeningTime
{
    public DayOfWeek DayOfWeek { get; set; }
    public DateTime OpeningTime { get; set; }
    public DateTime ClosingTime { get; set; }
}

So my fictional "shop" class would be something like this:

public class Shop
{
    public string Name { get; set; }
    public string Address { get; set; }
    public List<OpeningTime> OpeningTimes { get; set; }
}

Is DateTime still correct for representing something like:

Monday - 9:00 - 17:30

like image 714
Alex Avatar asked Dec 23 '22 00:12

Alex


1 Answers

Stick with DateTime

I would just use DateTime as it maps nicely to SQL (SQL uses DateTime also) and I find it's more readable than using TimeSpan. You can also use the same object and add a date to it to get Today's opening times for example.

Why not TimeSpan?

Because of it's name really and what that implies. TimeSpan represents a period of time as opposed to a point in time. Although it is used in the framework to represent an exact time (in TimeOfDay), but that property is defined in the docs as:

A TimeSpan that represents the fraction of the day elapsed since midnight.

But... doesn't really matter much

In the end it makes little difference, you can use TimeSpan, DateTime or your own struct. There is little overhead of either, it just comes down to what you find more readable and easier to maintain.

like image 167
badbod99 Avatar answered Jan 03 '23 05:01

badbod99