Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image

    Sven Groot said:
    the_corona said:

    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.

    It's a pity that .NET doesn't make a distinction between "data strings" and "display strings". I mean, instead of ToString() you'd have ToDataString() which returns a culture-independent string of data, and ToDisplayString() which returns a culture-dependent string used for display purposes.

    In my own code, I've created some static classes with extension methods to convert values (int, long, DateTime, ...) to data strings and back. You can then write code like this:

    DateTime d = DateTime.Today;
    string s = d.ToDataString(); // s will be "2009-12-29"
    d = s.ToDateTime();

    It also knows about nullable values, so you can use s.ToDateTimeOrNull() or convert nullable DateTime to data string.

    You can find the code on CodePlex (in folder TC/src/TC.Core in the files ConvertXXX.cs).