Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image
    Sven Groot

    the_corona said:
    Sven Groot said:

    ah, yes thats interesting, though I've never seen this before. I have to wonder though why you need to specify culturinvariant in that example given you very specifically ask for ddMMyyyy ?


    But come to think of it, Date.ToString I think also has an overload to do the formating the way you want, so even something like myDate.ToString("ddMMYYYY") - (I'm not sure of the exact syntax) - could get you a culture invariant string.


    Thinking about this more. does the {0:xx} in string.format end up as a string parameter to the first argument's ToString(string format)

    overload? So it ends up like

    string.format("{0:xx}", myDate) == string.format("{0}", myDate.ToString("xx"));

    Does this work in general or only with DateTime?



    You need to specify InvariantCulture because even with a simple format like that it might have unexpected results if you use the current culture. For instance, the culture might not even use the western calendar!


    For example, if I do this:

    CultureInfo culture = new CultureInfo("ja-JP");
    // Japanese culture settings uses Western calendar by default; might not be true for all cultures though.
    culture.DateTimeFormat.Calendar = new JapaneseCalendar();
    Thread.CurrentThread.CurrentCulture = culture;
    string result = myDate.ToString("ddMMyyyy");


    In this case, I've changed the current culture to something that uses a different calendar. Now, if myDate is December 29th 2009, the string result will be "291221". Why? Because on the Japanese calendar, the current year is Heisei 21.


    It's easily imaginable that on some system, somewhere, the default culture will be set to something that doesn't produce the correct result even with the format string "ddMMyyyy". That's why you always specify the InvariantCulture if you need a specific result, even if you think it doesn't matter.