DateTime to string conversion in C#

Introduction


In order to convert a dateTime object to a string , we use the ToString method.

DateTime date = new DateTime(2018, 11, 24, 13, 30, 15); // Initializing a new instance of the DateTime object

string text = date.ToString(); // 11/24/2018 1:30:15 PM

Format specifier


In order to customize the default date and time format string, we use a Format specifier.

DateTime date = new DateTime(2018, 11, 24, 13, 30, 15); // Initializing a new instance of the DateTime object

string text = date.ToString("d"); // 11/24/2018

In preceding code, we pass the Format specifier as a parameter of the ToString method.
The following table illustrates all standard format specifiers with their equivalent string representations :

d 11/24/2018
D Saturday, November 24, 2018
f Saturday, November 24, 2018 1:30 PM
F Saturday, November 24, 2018 1:30:15 PM
g 11/24/2018 1:30 PM
G 11/24/2018 1:30:15 PM
m November 24
r Sat, 24 Nov 2018 13:30:15 GMT
o 2018-11-24T13:30:15.0000000
s 2018-11-24T13:30:15
t 1:30 PM
T 1:30:15 PM
u 2018-11-24 13:30:15Z
U Saturday, November 24, 2018 1:30:15 PM
Y November 2018

Besides using standard format specifiers, we can also use custom format specifiers :

DateTime date = new DateTime(2018, 11, 24, 13, 30, 15); // Initializing a new instance of the DateTime object

string text1 = date.ToString("dd/MM/yyyy"); // 24/11/2018
string text2 = date.ToString("HH:mm:ss"); // 13:30:15

In preceding code, we pass the Format specifier as a parameter of the ToString method.
For more information about custom format specifiers, see Custom Date and Time Format Strings

Different Culture


In order to convert a dateTime object to a different culture, we use the CultureInfo object.

CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");
DateTime date = new DateTime(2018, 11, 24, 13, 30, 15); // Initializing a new instance of the DateTime object

string text = date.ToString("d", culture); // 24/11/2018

In preceding code, we create a new culture by passing the name of the french culture as a parameter of the CreateSpecificCulture method. After that, we convert our dateTime object by passing the format specifier and the french culture as parameters of the ToString method.

See .NET Framework Cultures for a list of all possible culture names.

Namespace


To use the CultureInfo object, you have to include the following namespace :

using System.Globalization;