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.
The DateTime struct includes the following methods that return date and time as a string.
METHODS | DESCRIPTION |
DateTime.ToString() | Converts a DateTime value to a string in the specified format of the current culture. |
DateTime.ToShortDateString() | Converts a DateTime value to a short date string (M/d/yyyy pattern) in the current culture. |
DateTime.ToShortTimeString() | Converts a DateTime value to a short time string (h:mm:ss pattern) in the current culture. |
DateTime.ToLongDaeString() | Converts a DateTime value to a long date string (dddd, MMMM d, yyyy pattern) in the current culture. |
DateTime.ToLongTimeString() | Converts a DateTime value to a long time string (h:mm:ss tt pattern) in the current culture. |
Convert DateTime to String using the ToString() Method
using System;
using System.Globalization;
using System.Threading;
public class Program
{
public static void Main()
{
var todayDate = DateTime.Today;
string strToday = todayDate.ToString(); // converts date to string as per current culture
Console.WriteLine("Date String in Default: " + strToday);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string strTodayUS = todayDate.ToString(); // converts date to string in MM/DD/YYYY format
Console.WriteLine("Date String in en-US Culture: " + strTodayUS);
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
string strTodayFR = todayDate.ToString(); // converts date to string in DD/MM/YYYY format
Console.WriteLine("Date String in fr-FR Culture: " + strTodayFR);
}
}
Output:
Convert DateTime to String in Specific Format
using System;
public class Program
{
public static void Main()
{
var dt = DateTime.Now;
Console.WriteLine("Date String Current Culture: " + dt.ToString("d"));
Console.WriteLine("MM/dd/yyyy Format: " + dt.ToString("MM/dd/yyyy"));
Console.WriteLine("dddd, dd MMMM yyyy Format: " + dt.ToString("dddd, dd MMMM yyyy"));
Console.WriteLine("MM/dd/yyyy h:mm tt Format: " + dt.ToString("MM/dd/yyyy h:mm tt"));
Console.WriteLine("MMMM dd Format:" + dt.ToString("MMMM dd"));
Console.WriteLine("HH:mm:ss Format: " + dt.ToString("HH:mm:ss"));
Console.WriteLine("hh:mm tt Format: " + dt.ToString("hh:mm tt"));
}
}
Output:
The Tech Platform
Commentaires