C# Datetime

The DateTime data type is used to represent, date and time in C#. If you have started coding in C# or you are already programming in C#, you will need to use Datetime data type somewhere in your application.

C# Datetime class provide many properties which we can use to get date, time, week, day etc of a particular datetime value.

Suppose, you want to get current date and time, then you can simply use the code below

		DateTime CurrentDT= DateTime.Now;
		Console.WriteLine(CurrentDT);
  //output: 12/25/2019 02:43:37 PM

Get Current Date from Datetime

If you want to extract only date from the above date & time, you can do it like

Console.WriteLine(CurrentDT.ToString("d"));
//output : 12/25/2019

If you want the date to be formatted into UK based date format "dd/MM/yyyy", you can do it by calling.ToString and passing the format like below

Console.WriteLine(CurrentDT.ToString("dd/MM/yyyy"));
//output: 25/12/2019

In the above code "dd/MM/yyyy" is the format of the output date which we need, where

dd= date in 2 digit

MM = month in 2 digit

yyyy = year in 4 digits

Get Current Time from Datetime

Now, if we need to extract only time part from the above Date and time, we can get it by using formatting

//only time 
Console.WriteLine(CurrentDT.ToString("hh:mm:ss tt"));
//output 02:43:37 PM

where,

hh= hours in 2 digit

mm= minutes in 2 digit

ss= seconds in 2 digit

tt = AM/PM

using System;
					
public class DateTimeProgram
{
	public static void Main()
	{
		DateTime CurrentDT= DateTime.Now;
		//complete datetime
		Console.WriteLine(CurrentDT);
		//only date
		Console.WriteLine(CurrentDT.ToString("d"));
		// only date with formatted type
		Console.WriteLine(CurrentDT.ToString("dd/MM/yyyy"));
		
		//only time 
		Console.WriteLine(CurrentDT.ToString("hh:mm:ss tt"));
		
	
	}
}

Output:

12/25/2019 2:43:37 PM
12/25/2019
25/12/2019
02:43:37 PM

To extract just hours, minutes, and seconds, you can use it as

Console.WriteLine(CurrentDT.Hour); //gives output as hour part, 02
Console.WriteLine(CurrentDT.Minute); // gives output as minutes part, 55
Console.WriteLine(CurrentDT.Second); //gives output as seconds part, 33

Here are few methods/property which we can use with Datetime variable, with it's description:

Property Name/ Method Description
ToLongDateString Print out date in following format: 25 December 2019
ToShortDateString Prints out the date in short format: 25/12/2019
ToLongTimeString Gives output as 02:43:37 (hour, minutes, seconds)
ToShortTimeString Gives output as 02:43 (hour and minutes)
Now Gets the current date and time
Day Gets the current day of Month (E.g. today is 25th Dec so it will get 25)
Year Get's the year ( Ex: 2019)
Month Get's the Month (Ex: 12)
DayofWeek Get's the Day of week (Ex: Wednesday)
Hour Gets the current hour
Minute Gets the current minute
AddHours Adds hours to the current time
AddDays Adds days to the current day
AddMonth Adds months to the current month
AddYear Adds year to the current year

There are lot more, but above one are widely used, for full reference check https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8#methods

Parsing Datetime in C# ( Convert String to Datetime )

You may get value as string and want to convert string into Datetime, then you can use methods like .Parse() and .ParseExact() and get Datetime value.

Suppose, date value as string

string dateStr= "25/12/2019";

now you need it's value as "Datetime", then you can use .Parse() or ParseExact() methods

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent.

Example:

using System;
					
public class DateTimeProgram
{
	public static void Main()
	{
      // Use standard en-US date and time value
	  DateTime dateValue;
      string dateString = "12/25/2019";
     
      dateValue = DateTime.Parse(dateString);
      Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      
            
	}
}

Output

'12/25/2019' converted to 12/25/2019 12:00:00 AM.

With using .ParseExact()

DateTime OutputDate= DateTime.ParseExact(dateString , "dd/MM/yyyy", CultureInfo.InvariantCulture);

In the above line of code, we are using DateTime.ParseExact to convert string date into Datetime value, Where

dateString = date as string value

dd/MM/yyyy=  fomrat of string date, which we will pass

CultureInfo.InvariantCulture = specifies the System.Globalization.CultureInfo, which is set to InvariantCulture, an invariant culture is culture-insensitive.  You can read more about CultureInfo here: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netframework-4.8#Invariant

Now, suppose we have this type of datetime value in string

string dateTimeStr= "25/12/2019 02:03";

then ,we can also parse the above string with time value using .ParseExact()

DateTime output= DateTime.ParseExact(dateTimeStr, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);

Share Tweet