Learn About DateTime Struct In C#

Introduction

In C#, we can use the DateTime struct to perform date and time-related operations. DateTime 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.

DateTime date = DateTime.Now;

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

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

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

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

To assign a maximum date and time range.

date = DateTime.MaxValue;

date time range

Display DateTime Object

You can display the DateTime object as simply as.

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

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

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

display date time

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

Console.WriteLine("Year = " + date.Year);
Console.WriteLine("Month = " + date.Month);
Console.WriteLine("Date = " + date.Date);
Console.WriteLine("Day = " + date.Day);
Console.WriteLine("Day of Week = " + date.DayOfWeek);
Console.WriteLine("Day of Year = " + date.DayOfYear);
Console.WriteLine("Time of Day = " + date.TimeOfDay);
Console.WriteLine("Hour = " + date.Hour);
Console.WriteLine("Minute = " + date.Minute);
Console.WriteLine("Second = " + date.Second);
Console.WriteLine("Millisecond = " + date.Millisecond);

Note. To display today's date only without month and year, use “Day” as the 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

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

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

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

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

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

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

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

C#

Here is a detailed tutorial, DateTime In C#.


Similar Articles