Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Date without Time - is there one, or should I not need one? [duplicate]

I'm doing some domain modelling and coming across a property which to my mind would be best exposed as a Date rather than a DateTime, without a time component.

Is there a good reason why there is no such type in the Framework? It was deemed a good enough idea to add a Date type to SQL Server. Also, if someone knows of a handy implementation of a Date class, please let me know!

2018 edit: I now tackle this using a Value Object Type:

public class Date : ValueOf<DateTime, Date>  //Install-Package ValueOf {      protected override void Validate()      {          if (Value.Date != Value) throw new ArgumentException();      }  }  ...  var date = Date.From(someDateTime); 
like image 843
mcintyre321 Avatar asked Aug 23 '11 21:08

mcintyre321


People also ask

How do I get the current date without time?

var dateAndTime = DateTime. Now; var date = dateAndTime. Date; variable date contain the date and the time part will be 00:00:00.

Why DateTime is a structure?

The actual data in a DateTime is a single long integer. If it were a class, every time you created a new object, 8 bytes would be allocated on the heap and another 8 bytes would be allocated on the stack for the pointer. So by making a DateTime a struct, it effectively cuts the memory requirements in half.

Which of the following is a static property of DateTime class?

The comparer static method is used to compare the object of the two datetime. If the objects of both DateTime is the same, then the result will be 0. If the first DateTime is earlier, then the result will be 0 else the first DateTime would be later.


Video Answer


2 Answers

No, there isn't one, and yes, there should be.

I don't believe there's a good reason other than that the date and time API in .NET isn't very good in my (very biased) view.

I'm working on a new API called Noda Time which of course does have a date-only class in (LocalDate) but it's not ready for production yet. It may already do everything you need it to, of course, and if it nearly does then you could always ask for just the features you need to be implemented sooner rather than later...

like image 73
Jon Skeet Avatar answered Oct 08 '22 13:10

Jon Skeet


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/claycephas/csharp-date

like image 26
Clay Avatar answered Oct 08 '22 13:10

Clay