I know how to format a DateTime
as a String
. There may be many ways to format a DateTime
as a String
, and I have found few questions related to DateTime
formatting.
But I found and tried two ways:
GetDateTimeFormats()
ToString("MM/dd/yyyy")
I tried this code:
public static class DateTimeFormates
{
public static string FormatMyDate(this DateTime DT)
{
// My Actual Date Time Comes in this Format
//8/23/2013 12:43:12 PM
// I'm expecting Format like below
String FormatWayOne = DT.GetDateTimeFormats()[3];
//08/23/2013
String FormatWayTwo = DT.ToString("MM/dd/yyyy");
//08/23/2013
return FormatWayOne;
}
}
I have a Global
class with Global
method to format a DateTime
as a String
. But here what I want to know which method is the best practice so I can use it? The method is called all over the application.
Convert DateTime to String using the ToString() MethodUse the DateTime. ToString() method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.
GetDateTimeFormats
is not a replacement for ToString
and vice versa. If you know what format you want, there's no need to call GetDateTimeFormats
. As well as it being clearer to use ToString
, the document for GetDateTimeFormats
states this (emphasis mine)
Because this method uses culture-sensitive data, you should not assume that multiple calls to the method will return identical data. The data returned by this method can change if the current culture changes, the user overrides individual cultural settings, or an update occurs to the system's cultural data.
This could potentially break your code as the third element could be something else when run in another culture.
By using ToString, you're avoiding having to loop through all date formats (hence being more efficient) and you're making it clearer as to what format you like whilst ensuring that the format returned is the one you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With