Remove time part from C# DateTime object
When dealing with dates in C#, you may encounter scenarios where you only need the date part but not the time information. This is often necessary when dealing with entities that only store or process date values.
Regarding removing time from a DateTime object, the following issues arise:
Question:
How to remove the time portion of a DateTime object in C# without relying on string conversion methods?
Solution:
To remove the time component from a DateTime object, use the Date property. Its syntax is as follows:
<code class="language-csharp">var date = dateAndTime.Date;</code>
Here, dateAndTime represents the original DateTime object containing date and time information. By calling the Date property, a new DateTime object named date is created that contains only the date portion and the time portion set to 00:00:00.
Example:
<code class="language-csharp">var dateAndTime = DateTime.Now; Console.WriteLine(dateAndTime); // 输出:2023-10-27 10:23:45 var date = dateAndTime.Date; Console.WriteLine(date); // 输出:2023-10-27 00:00:00</code>
As you can see, the date variable now contains the date part without any time information, and the time is automatically set to midnight.
The above is the detailed content of How to Remove the Time Portion from a DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!