I want to get only the date part of the datetime. This is what I am reading from the database:
{5/12/2023 12:19:05 PM}
This is what I tried to do:
DateTime createDate = Convert.ToDatetime(System.DateTime.Now.ToShortDateString())
with above code, CreateDate has value of; 5/12/2023 12:00:00
I also tried :
DateTime createDate = Convert.ToDatetime(System.DateTime.Now.ToString().Substring(0,10));
this also appends 12:00:00 at the end of the data string. How can I get only the date part in a variable of type DateTime.
>Solution :
Imagine you had a Name struct like this:
public struct Name
{
public string LastName {get;set;}
public string FirstName {get;set;}
}
Now say you want an instance of this struct with no FirstName property. You could get an instance with an empty string in the property, or a null value in the property, but the property is still there. You can’t remove the property completely without fundamentally changing the type definition.
DateTime values are similar. They always have a time portion. You can’t get ride of it; it’s a fundamental part of the value. Since it’s a value type, you can’t even make it null. The best you can do construct a version of the value with the time portion set to all zeros (midnight), like this:
DateTime createDate = DateTime.Now.Date
or
DateTime createDate = DateTime.Today
Then configure your output/presentation code to not show the time part, usually with a format string. But again: don’t worry about this until right at the moment when you want to output the data, and if you’re only writing out the Date portion anyway you can probably just skip checking the .Date property completely: the format string can be crafted to only show the part you care about from the full original value.
More recently, .Net also added a DateOnly type:
DateOnly createDate = DateOnly.FromDateTime(DateTime.Now);