
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Only Date Portion from DateTime Object in C#
There are several ways to get only date portion from a DateTime object.
ToShortDateString() ? Converts the value of the current DateTime object to its equivalent short date string representation.
Returns a string that contains the short date string representation of the current DateTime object.
ToLongDateString() ? Converts the value of the current DateTime object to its equivalent long date string representation.
Returns a string that contains the long date string representation of the current DateTime object.
ToString() ? One more way to get the date from DateTime is using ToString() extension method.
The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch.
DateTime.Date ? will also remove the time from the DateTime and provides us the Date only.
The difference of this method from the above example is that, here the date is not converted to a string.
Example using extensions methods of DateTime ?
Example
using System; namespace DemoApplication{ public class Program{ public static void Main(){ var dateTime = DateTime.Now; Console.WriteLine($"DateTime Value: {dateTime}"); var shortDateValue = dateTime.ToShortDateString(); Console.WriteLine($"Short Date Value: {shortDateValue}"); var longDateValue = dateTime.ToLongDateString(); Console.WriteLine($"Long Date Value: {longDateValue}"); Console.ReadLine(); } } }
Output
The output of the above program is
DateTime Value: 07-08-2020 21:36:46 Short Date Value: 07-08-2020 Long Date Value: 07 August 2020
Example using DateTime.Date ?
Example
using System; namespace DemoApplication{ public class Program{ public static void Main(){ var dateTime = DateTime.Now; Console.WriteLine($"DateTime Value: {dateTime}"); var dateValue = dateTime.Date; Console.WriteLine($"Date Value: {dateValue}"); Console.ReadLine(); } } }
Output
The output of the above code is
DateTime Value: 07-08-2020 21:45:21 Date Value: 07-08-2020 00:00:00
Example using ToString() extension method ?
Example
using System; namespace DemoApplication{ public class Program{ public static void Main(){ var dateTime = DateTime.Now; Console.WriteLine($"DateTime Value: {dateTime}"); var dateValue1 = dateTime.ToString("MM/dd/yyyy"); Console.WriteLine($"Date Value: {dateValue1}"); var dateValue2 = dateTime.ToString("dd/MM/yyyy"); Console.WriteLine($"Date Value: {dateValue2}"); var dateValue3 = dateTime.ToString("d/M/yy"); Console.WriteLine($"Date Value: {dateValue3}"); Console.ReadLine(); } } }
Output
The output of the above code is
DateTime Value: 07-08-2020 21:58:17 Date Value: 08-07-2020 Date Value: 07-08-2020 Date Value: 7-8-20