Trusted answers to developer questions

How to convert a DateTime object to a string in C#

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

Syntax

The syntax of the ToString method is:

svg viewer

Code

The code snippet below illustrates the usage of the ToString method:

using System;
class ToStringDemo
{
static void Main()
{
// create date time 2019-11-12 22:45:12.004
DateTime date = new DateTime(2019, 11, 12, 22, 45, 12, 004);
// converting to string format
string date_str = date.ToString("dd/MM/yyyy HH:mm:ss");
Console.WriteLine(date_str);
}
}

RELATED TAGS

datetime
string
convert
format
c#
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?