How to Converting DateTime to Strings?
The ToString
method is used to converting a DateTime
object to a string in C#. This method allows you to format the date and time according to specific patterns.
using System;
class Program
{
static void Main()
{
// Creating a DateTime object representing the current date and time
DateTime currentDateTime = DateTime.Now;
// Converting DateTime to strings using various formats
string shortDate = currentDateTime.ToString("d");
string longDate = currentDateTime.ToString("D");
string customFormat = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
// Displaying the results
Console.WriteLine("Short Date Format: " + shortDate);
Console.WriteLine("Long Date Format: " + longDate);
Console.WriteLine("Custom Format: " + customFormat);
Console.ReadKey();
}
}
In this program, we have created a DateTime
object representing the current date and time using DateTime.Now
. We then used the ToString
method with different format specifiers to convert the DateTime
object to strings.
Output:
Short Date Format: 02-07-2024
Long Date Format: 02 July 2024
Custom Format: 2024-07-02 21:43:12
Comments (0)