Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Obtaining only date part of the datetime

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading