Should I use ToString() or GetDateTimeFormats() to format a DateTime?

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:

  1. GetDateTimeFormats()
  2. 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.

Answers


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.


ToString is clearer, and also it doesn't use a magic number that might not work in the next framework version/another culture. Use ToString().


Which one is Good Practice or Best way

Both are good for their own needs.

difference between this two ways?

GetDateTimeFormats()

Converts the value of this instance to all the string representations supported by the standard date and time format specifiers. Which means it is an expensive operation and getting the third element each time may give you different results. You don't need to convert to all formats so why do so?

ToString()

Converts the value of the current DateTime object to its equivalent string representation using the specified format.

Any Suggestions or Ideas?

As Second method (ToString) is only converting to your required format and is more readable as well. Hence preferrable. Whereas, if you use the first method you will be converting to around 100 formats when you require only one.


I prefer ToString(format) version only. but not the format you shown as example. It can screw you across the culture. Let's take a look at following example.

    DateTime now = DateTime.Now;

    string fmt1 = now.ToString("MM/dd/yyyy"); // MM/dd/yyyy
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us")
    { 
        DateTimeFormat=
        {
            DateSeparator = "-"
        }
    };
    string fmt1a = now.ToString("MM/dd/yyyy"); // MM-dd-yyyy (you're in trouble when you want to deserialize)

    string fmt2 = now.ToString("MMddyyyy"); // MMddyyyy
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us")
    {
        DateTimeFormat =
        {
            DateSeparator = "-"
        }
    };
    string fmt2a = now.ToString("MMddyyyy"); and // MMddyyyy always

Am not going to talk about GetDateTimeFormats here since it is a overkill.

Wondering how fmt1a can return MM-dd-yyyy when you say MM/dd/yyyy ? because / is a special character which is used to represent DateTimeFormatInfo.DateSeperator of current culture.

So, I'll suggest you to use custom formatting without / for serialization and any other formatting for UI.


I've been using .ToString(format) for years, and it's never let me down. You can use built in formats, or customize your own.


If you only want the date and as I see, the culture format is correct, just use the datetime method ToShortDateString

MyDateTime.ToShortDateString();

But using this in an extesion method doesn't make any sense. If you want to convert any date in any format to always display in MM/dd/yyyy you should first set then culture and the call the method.

Check here for the proper code to use http://msdn.microsoft.com/es-es/library/system.datetime.toshortdatestring.aspx


Need Your Help

Paypal Adaptive Payment API Custom Variable IPN Return

php paypal paypal-ipn

I am trying to do Adaptive Payment API with a IPN and have been find that with the sandbox environment I'm not getting back payer's address or custom variables. I've seen this in another post with

Getting .value of Dynamic Element

javascript jquery

I'm pretty new to jQuery and javascript so go easy on me. I have a select box with the id="select-cat". This select box is being created dynamically so I went ahead and used the .on event handler l...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.