DateTime Class in C#

Introduction

In C#, to perform Date & Time-related information and operations, we have a few Classes like DateTime. Let us see them in detail.

DateTime class is present in System namespace.

DateTime class can be instantiated by different methods.

Note : I have documented this article on 13-05-2018 (May 13, 2018). Hence, this date value will be used throughout.

To get today’s date, use DateTime.Now.

  1. DateTime date = DateTime.Now;  

You can pass Year, Month and Date as parameter, which creates assigned date with time as 12 AM.

  1. date = new DateTime(1990, 01, 23);  

To create a date with specified time, pass Hour, Minute and Seconds in addition to above parameters. Time will be in 24 hours format.

  1. date = new DateTime(1990, 01, 23, 23, 10 , 10);  

To assign maximum date and time range.

  1. date = DateTime.MaxValue;  
C#

Display DateTime Object

You can display DateTime object as simply as:

  1. date = DateTime.Now;  
  2. Console.WriteLine("Date = " + karthi);  

It is recommended to always use ToString() method to display the Date.

  1. Console.WriteLine("Date = " + date.ToString());  
C#

To Display Year, Month, Date, Hour, Minute, Second

  1. Console.WriteLine("Year = " + date.Year);  
  2. Console.WriteLine("Month = " + date.Month);  
  3. Console.WriteLine("Date = " + date.Date);  
  4. Console.WriteLine("Day = " + date.Day);  
  5. Console.WriteLine("Day of Week = " + date.DayOfWeek);  
  6. Console.WriteLine("Day of Year = " + date.DayOfYear);  
  7. Console.WriteLine("Time of Day = " + date.TimeOfDay);  
  8. Console.WriteLine("Hour = " + date.Hour);  
  9. Console.WriteLine("Minute = " + date.Minute);  
  10. Console.WriteLine("Second = " + date.Second);  
  11. Console.WriteLine("Millisecond = " + date.Millisecond);  

Note
To display today's date only without month and year, use “Day” as date and it will return the assigned date value and reset time to 12 AM.

C#

To Display Short Version of Date. Ex: 13-05-2018

  1. Console.WriteLine("Short Date = " + date.ToShortDateString());  

To Display Long Version of Date. Ex: 13 May 2018

  1. Console.WriteLine("Long Date = " + date.ToLongDateString());  

To Display Short Version of Time. Ex: 13:00

  1. Console.WriteLine("Short Time = " + date.ToShortTimeString());  

To Display Long Version of Time. Ex: 13:00:00

  1. Console.WriteLine("Long Time = " + date.ToLongTimeString());  

C#