Search code examples
c#.netdatetimelocale

C# - Am I replacing perfectly good code?


I had a quick function to format a date, here it is:

public static string archiveServerDateTime(string datetime)
    {
        DateTime tempDateTime = DateTime.ParseExact(datetime,"dd.MM.yyyy HH:mm:ss", null);
        return tempDateTime.ToString("yyyy/MM/dd:HH:mm:ss");
    }

only to find the output of the function = 2009.10.22:16:21:03, and amazingly this is only on 1 production server, test server worked perfectly fine......

So now I rewrote the function to old school style:

public static string archiveServerDateTime(string datetime)
    {
        DateTime tempDateTime = DateTime.ParseExact(datetime,"dd.MM.yyyy HH:mm:ss", null);
        string yearPart = Convert.ToString(tempDateTime.Year);
        string monthPart = Convert.ToString(tempDateTime.Month).PadLeft(2,'0');
        string dayPart = Convert.ToString(tempDateTime.Day ).PadLeft(2, '0');
        string hourPart = Convert.ToString(tempDateTime.Hour).PadLeft(2, '0');
        string minutePart = Convert.ToString(tempDateTime.Minute).PadLeft(2, '0'); 
        string secondPart = Convert.ToString(tempDateTime.Second).PadLeft(2,'0');

        return yearPart + @"/" + monthPart + @"/" + dayPart + ":" + hourPart + ":" + minutePart + ":" + secondPart; 
        //return tempDateTime.ToString("yyyy/MM/dd:HH:mm:ss");
    }

So I ask you ladies and gentlemen, was I replacing perfectly good code to begin with, or is this a Microsoft bug of some kind? Can we really trust these new language features that are seemingly not so rock solid, or am I just missing something?


Solution

  • You should pass DateTimeFormatInfo.InvariantInfo as an argument to the DateTime.ToString method. / in the format string does not mean "/" character all the time. It resolves to the date separator of the current culture:

    return tempDateTime.ToString("yyyy/MM/dd:HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
    

    In general, it's a good practice to always clearly specify the culture in ToString and Parse methods (not only on DateTimes). FxCop (VS Code Analysis) has rules that spit out warnings when you don't do this. It's critical for non-US cultures and the importance is often underestimated by many programmers.