How to format the HH:mm:ss separators of a TimeSpan in a culture-aware manner?

前端 未结 3 1281
谎友^
谎友^ 2021-01-05 05:33

I\'m working on an app that may be seen in many countries in the world. There are not many countries that show hours, minutes and seconds with something other than : as a s

3条回答
  •  梦毁少年i
    2021-01-05 06:05

    This is more like a comment, but needs some space, so I write it as an answer.

    While string formatting of DateTime has been in .NET for a very long time, formatting of TimeSpan was new in .NET 4.0 (Visual Studio 2010).

    A culture has a DateTimeFormatInfo object which is used by DateTime and includes info on whether to use colon : or period . or something else between hours, minutes and seconds. Now, TimeSpan does not seem to use this DateTimeFormatInfo object, and there is nothing called "TimeSpanFormatInfo".

    Here's an example:

    // we start from a non-read-only invariant culture
    Thread.CurrentThread.CurrentCulture = new CultureInfo("");
    
    // change time separator of DateTime format info of the culture
    CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator = "<-->";
    
    var dt = new DateTime(2013, 7, 8, 13, 14, 15);
    Console.WriteLine(dt);  // writes "07/08/2013 13<-->14<-->15"
    
    var ts = new TimeSpan(13, 14, 15);
    Console.WriteLine(ts);  // writes "13:14:15"
    

提交回复
热议问题