129

In our C# project we have the need for representing a date without a time. I know of the existence of the DateTime, however, it incorporates a time of day as well.

  • I want to make explicit that certain variables and method-arguments are date-based.
  • Hence I can't use the DateTime.Date property

What are the standard approaches to this problem?

  • Why is there no Date class in C#?
  • Does anyone have a nice implementation using a struct and maybe some extensionmethods on DateTime and maybe implementing some operators such as == and <, > ?
7
  • 1
    While I understand wanting explicit, clear semantics, what specific problems does DateTime create? Mar 15, 2011 at 15:55
  • 24
    1 I need to remember to remove the hours at the start of the method. 2 it does not communicate well that it works solely on dates. This is important eg when storing and loading from Db where a narrow type will suffice. Programming is communion for people not computers Mar 15, 2011 at 22:38
  • 14
    I just wanted to say that the lack of a date class IS a big deal and using DateTime no good at all. As soon as you store your "dates" as date-time you are hostage to locale/timezone daylights savings issues. Throwing away the time part can send all your dates back a day when the clocks change(!). And users in different timezones will see different dates when they try to convert the date-times. Date-times are fine for representing precise moments in time (jiffies from some point or whatever) but they are very unsuitable for representing an abstract date. Jan 31, 2012 at 16:55
  • 4
    A later similar question stackoverflow.com/questions/7167710/…, and Jon Skeet says there should be a Date.
    – goodeye
    Nov 25, 2012 at 2:22
  • 14
    A date only data type is to DateTime as an integer data type is to a decimal. Those who argue we do not need a date because you can just throw away the time part is akin to saying we do not need integers as we can throw away the decimal part. Our world has a concept of a date that does not include a time. 5 March is not 5 March 00:00:00.
    – Vague
    Mar 14, 2016 at 3:07

14 Answers 14

90

Allow me to add an update to this classic question:

  • DateOnly (and TimeOnly) types have been added to .NET 6, starting with Preview 4. See my other answer here.

  • Jon Skeet's Noda Time library is now quite mature, and has a date-only type called LocalDate. (Local in this case just means local to someone, not necessarily local to the computer where the code is running.)

I've studied this problem significantly, so I'll also share several reasons for the necessity of these types:

  1. There is a logical discrepancy between a date-only, and a date-at-midnight value.
  • Not every local day has a midnight in every time zone. Example: Brazil's spring-forward daylight saving time transition moves the clock from 11:59:59 to 01:00:00.

  • A date-time always refers to a specific time within the day, while a date-only may refer to the beginning of the day, the end of the day, or the entire range of the day.

  1. Attaching a time to a date can lead to the date changing as the value is passed from one environment to another, if time zones are not watched very carefully. This commonly occurs in JavaScript (whose Date object is really a date+time), but can easily happen in .NET also, or in the serialization as data is passed between JavaScript and .NET.

  2. Serializing a DateTime with XML or JSON (and others) will always include the time, even if it's not important. This is very confusing, especially considering things like birth dates and anniversaries, where the time is irrelevant.

  3. Architecturally, DateTime is a DDD value-object, but it violates the Single Responsibly Principle in several ways:

  • It is designed as a date+time type, but often is used as date-only (ignoring the time), or time-of-day-only (ignoring the date). (TimeSpan is also often used for time-of-day, but that's another topic.)

  • The DateTimeKind value attached to the .Kind property splits the single type into three, The Unspecified kind is really the original intent of the structure, and should be used that way. The Utc kind aligns the value specifically with UTC, and the Local kind aligns the value with the environment's local time zone.

    The problem with having a separate flag for kind is that every time you consume a DateTime, you are supposed to check .Kind to decide what behavior to take. The framework methods all do this, but others often forget. This is truly a SRP violation, as the type now has two different reasons to change (the value, and the kind).

  • The two of these lead to API usages that compile, but are often nonsensical, or have strange edge cases caused by side effects. Consider:

         // nonsensical, caused by mixing types
         DateTime dt = DateTime.Today - TimeSpan.FromHours(3);  // when on today??
    
         // strange edge cases, caused by impact of Kind
         var london = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
         var paris = TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time");
         var dt = new DateTime(2016, 3, 27, 2, 0, 0);  // unspecified kind
         var delta = paris.GetUtcOffset(dt) - london.GetUtcOffset(dt);  // side effect!
         Console.WriteLine(delta.TotalHours); // 0, when should be 1 !!!
    

In summary, while a DateTime can be used for a date-only, it should only do so when when every place that uses it is very careful to ignore the time, and is also very careful not to try to convert to and from UTC or other time zones.

1
14

I suspect there is no dedicate pure Date class because you already have DateTime which can handle it. Having Date would lead to duplication and confusion.

If you want the standard approach look at the DateTime.Date property which gives just the date portion of a DateTime with the time value set to 12:00:00 midnight (00:00:00).

8
  • 71
    A big advantage of a dedicated Date class is that it doesn't suffer from the complexities of time zones and daylight saving time.
    – Dimitri C.
    May 24, 2012 at 7:48
  • 3
    @DimitriC. I disagree - you can use DateTime with UTC and you do not suffer from the issues explained, plus with a DateTime, even if you want just dates you can still do math that involves time (i.e. give me the date if I subtract 20 x 2hour from today). May 24, 2012 at 11:32
  • 11
    Having to think about UTC and anything to do with timezone is just a waste of energy because it can easily be avoided by a separate Date class. And I don't see any confusion between Date and DateTime.
    – maulik13
    Feb 17, 2015 at 8:01
  • 6
    Agree that C# really should have a Date class. Not only is the time zone conversion thing a constant source of submarine bugs, but it's just plain painful when dealing with things that a business day based rather than time based. Jun 8, 2016 at 13:41
  • 2
    @RobertMacLean: it makes no sense to consider the "date if I subtract 20 x 2hour from today". In this example, do you consider today as "today at midnight"? "today at noon time"? etc. This problem is not well formulated. If you mean "today at midnight", you are already working with DateTime, not a Date. In order to subtract hours, you need an hour, not a day.
    – xavier
    Aug 18, 2020 at 9:43
14

I've emailed refsrcfeedback@microsoft.com and that's their answer

Marcos, this is not a good place to ask questions like these. Try http://stackoverflow.com Short answer is that you need a model to represent a point in time, and DateTime does that, it’s the most useful scenario in practice. The fact that humans use two concepts (date and time) to mark points in time is arbitrary and not useful to separate.

Only decouple where it is warranted, don’t do things just for the sake of doing things blindly. Think of it this way: what problem do you have that is solved by splitting DateTime into Date and Time? And what problems will you get that you don’t have now? Hint: if you look at DateTime usages across the .NET framework: http://referencesource.microsoft.com/#mscorlib/system/datetime.cs#df6b1eba7461813b#references You will see that most are being returned from a method. If we didn’t have a single concept like DateTime, you would have to use out parameters or Tuples to return a pair of Date and Time.

HTH, Kirill Osenkov

In my email I'd questioned if it was because DateTime uses TimeZoneInfo to get the time of the machine - in Now propriety. So I'd say it's because "the business rules" are "too coupled", they confimed that to me.

6
  • 1
    This post really gives insights in the thoughts behind the design decision of not having a built-in date class. What was the question you send them? I don't mean to imply that I agree with this decision for the very reasons that @TheMathemagician listed above. May 11, 2016 at 12:07
  • 4
    Maybe MS could just go the whole hog and implement a SpaceTime class! Hey, according to Einstein, space and time are tightly coupled so we shouldn't need to differentiate between them either, right? (!!!!!!!!!!!) I'm kinda new to C#, but I have to say, it's a minefield coming from VB.NET where is, simply, date, Today(), now, etc. No DateTime prefixing rubbish, no mucking about. (And these semicolons and this case-sensitivity sure is irksome! Just shoot me now!)
    – SteveCinq
    Nov 16, 2017 at 23:11
  • 4
    And their own SQL Server have Date type and result must be of type Date - if it was Date type result expected as string without time. For example Delphi also have Date as DateTime, but typeinfo different for Date and DateTime. Jul 18, 2018 at 11:45
  • 3
    Kirill Osenkov is answering the Q of "Why not have separate Date and Time Classes versus DateTime Class?". The actual Q was "Why not also have separate Date and Time Classes?". I understand that Date and Time should be coupled into one Class for the granted many use cases of the date-time concept. However, there are probably at least as many if not more so just as valid use cases of just a date concept. And of course there are many valid uses cases of a time concept also.
    – Tom
    May 14, 2019 at 20:13
  • 1
    This seems an odd answer given that SQL server has a DateTime, a Date and a Time type. Clearly we need these as separate entities for many real world applications. Sep 30, 2021 at 12:07
10

I created a simple Date struct for times when you need a simple date without worrying about time portion, timezones, local vs. utc, etc.

https://github.com/claycephus/csharp-date

0
8

System.DateOnly and System.TimeOnly types were recently added to .NET 6, and are available in the daily builds.

They were included with the .NET 6 Preview 4 release.

See https://github.com/dotnet/runtime/issues/49036

They are in the .NET source code here:

I've blogged about them here.

1
  • 6
    It was about time, if I may
    – GôTô
    Aug 3, 2021 at 21:38
4

If you need to run date comparisons then use

yourdatetime.Date;

If you are displaying to the screen use

yourdatetime.ToShortDateString();
1
  • The .Date part is what I was looking for. Oct 2, 2013 at 12:23
3

Allow me to speculate: Maybe it is because until SQL Server 2008 there was no Date datatype in SQL so it would be hard so store it in SQL server?? And it is after all a Microsoft Product?

4
  • A db datetime is different than a C# datetime. A db datetime does not have a timezone so they don't actually refer to a particular instant. But C# does know that the instant is and stores the ticks since the UTC epoch.
    – artsrc
    Sep 28, 2011 at 7:03
  • 2
    the discussion is about the dedicated DATE,not so much about the datetime part so I do not understand the point you are trying to make?
    – Pleun
    Sep 28, 2011 at 8:01
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
    – Barranka
    Jan 27, 2015 at 20:24
  • @Barranka - The question contains "Why is there no Date class in C#?"
    – STLDev
    Dec 7, 2015 at 22:05
2

Who knows why it's that way. There are lots of bad design decisions in the .NET framework. However, I think this is a pretty minor one. You can always ignore the time part, so even if some code does decide to have a DateTime refer to more than just the date, the code that cares should only ever look at the date part. Alternatively, you could create a new type that represents just a date and use functions in DateTime to do the heavy lifting (calculations).

6
  • 1
    I really do not think this was a bad decision, whether you want to use only a date or not. I won't downvote ya but that's my opinion.
    – JonH
    Mar 15, 2011 at 15:59
  • I don't think I worded it well. I don't actually have much of a problem with it, per se, although I could see how having two or three types would be more appropriate from an abstraction/elegance point of view. My point really was that there are a lot of things in the .NET framework that may leave you scratching your head and it's not worth getting too upset about, especially considering that this "issue" is pretty minor compared to some egregious design decisions (generic constraints).
    – siride
    Mar 15, 2011 at 16:01
  • +1 because it's true... was this the only problem (or the biggest one) of .NET :-) :-) How many versions of SQL Server did they need to add a DATE and a TIME types? And there they were MUCH more useful (at least for integrity reasons)
    – xanatos
    Mar 15, 2011 at 16:02
  • I should also add that I think the "everything starts at -100 points" is a good way to make a piss-poor framework and this may be one of the things that got caught up in that garbage.
    – siride
    Mar 15, 2011 at 16:04
  • 2
    I just got bitten by this issue because 1 part of the code neglected to use the .Date property and thus did not compare properly. I definitely think there is need for a Date type that does not store any time, to avoid this type of error
    – JoelFan
    Aug 14, 2012 at 15:30
2

Why? We can only speculate and it doesn't do much to help solve engineering problems. A good guess is that DateTime contains all the functionality that such a struct would have.

If it really matters to you, just wrap DateTime in your own immutable struct that only exposes the date (or look at the DateTime.Date property).

2

In addition to Robert's answer you also have the DateTime.ToShortDateString method. Also, if you really wanted a Date object you could always use the Adapter pattern and wrap the DateTime object exposing only what you want (i.e. month, day, year).

2

There is always the DateTime.Date property which cuts off the time part of the DateTime. Maybe you can encapsulate or wrap DateTime in your own Date type.

And for the question why, well, I guess you'll have to ask Anders Heljsberg.

1

Yeah, also System.DateTime is sealed. I've seen some folks play games with this by creating a custom class just to get the string value of the time as mentioned by earlier posts, stuff like:

class CustomDate
{
    public DateTime Date { get; set; }
    public bool IsTimeOnly { get; private set; }

    public CustomDate(bool isTimeOnly)
    {
        this.IsTimeOnly = isTimeOnly;
    }

    public string GetValue()
    {
        if (IsTimeOnly)
        {
            return Date.ToShortTimeString();
        }

        else
        {
            return Date.ToString();
        }
    }
}

This is maybe unnecessary, since you could easily just extract GetShortTimeString from a plain old DateTime type without a new class

0

Because in order to know the date, you have to know the system time (in ticks), which includes the time - so why throw away that information?

DateTime has a Date property if you don't care at all about the time.

1
  • 1
    Today is 2020-12-07; care to give an accurate system time in ticks for that date?
    – Taemyr
    Dec 7, 2020 at 10:20
0

If you use the Date or Today properties to get only the date portion from the DateTime object.

DateTime today = DateTime.Today;
DateTime yesterday = DateTime.Now.AddDays(-1).Date;

Then you will get the date component only with the time component set to midnight.

4
  • 1
    this is definitely not what i wanted Mar 15, 2011 at 16:04
  • @Carlo V. Dango: I disagree. I think it's exactly what you wanted.
    – siride
    Mar 15, 2011 at 16:06
  • 1
    @Carlo V. Dango: What are you specifically looking to do that these properties don't allow you to accomplish?
    – eph_tagh
    Mar 15, 2011 at 16:09
  • 5
    It's quite easy: a Date memory footprint would probably be only half the memory footprint of a DateTime (32 instead of 64 bits). You would be sure that your stupid coworker didn't .AddHours(1) to your date changing it but "keeping the same" from the POV of "date only". If (for an error) the DateTime is set to DateTimeKind.Local and the time is normalized to UTC, the Date will probably change (happened to me through the use of XmlSerialization and badly done roundtrip to JSON)... Is it enough?
    – xanatos
    Mar 15, 2011 at 16:48

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.