A Type for Date Only in C# - Why Is There No Date Type

Date vs DateTime

No there isn't. DateTime represents some point in time that is composed of a date and a time. However, you can retrieve the date part via the Date property (which is another DateTime with the time set to 00:00:00).

And you can retrieve individual date properties via Day, Month and Year.

UPDATE: In .NET 6 the types DateOnly and TimeOnly are introduced that represent just a date or just a time.

How to remove time portion of date in C# in DateTime object only?

Use the Date property:

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;

The date variable will contain the date, the time part will be 00:00:00.

Which C# datatype should be used to store dates without time?

DateTime doesn't have timezone info, only a generic UTC/"Local" indicator.

There is no date- or time-only type in .NET at the time. While the lack of Date is an inconvenience, the lack of TimeOfDay is a bigger problem. People are experimenting with Date and TimeOfDay types though at the CoreFX Lab repository.

At the moment you'll have to use the DateTime class or create your own Date class. Even the SQL Server ADO.NET provider doesn provide a date or time only class.

Of course you can always "borrow" the MIT-licensed experimental Date implementation from CoreFX Lab.

NOTE

I understand the pain and the need as I work on air travel related software. Having to work with timezones when I only want to compare against a date is really tiresome. Things begin to really ---- though when I need to convert between Json and DateTime to pass date only values.

Is there only a Date type like TimeSpan instead of DateTime?

There is not. Closest thing, if you must ensure there's no time data attached to your DateTime object, is to use the DateTime.Date property, whose return value is another DateTime, but with the time value set to 00:00:00 (midnight).

And of course, when displaying the date, you can control its formatting as you like.

In particular, the Short Date specifier:

var dateValue = new DateTime(2011, 10, 14);
dateValue.ToString("d");

Will output 10/14/2011 in the Invariant culture.

How to cast TimeOnly to DateTime in C#?

Since TimeOnly holds no date information, you'll need a reference date, then add the time contained in the TimeOnly object by using the ToTimeSpan method.

TimeOnly timeOnly = new TimeOnly(10, 10, 10);
var referenceDate = new DateTime(2022, 1, 1);
referenceDate += timeOnly.ToTimeSpan();
Console.WriteLine(dateTime); // 1/1/2022 10:10:10 AM


Related Topics



Leave a reply



Submit