Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a DateTime to a string with fractional seconds that is localized?

I have a DateTime object and I want to output the hour, minute, second, and fractional second as a string that is localized for the current culture.

There are two issues with this.

First issue is there is no standard DateTime format that will show the fractional seconds. I essentially want to know how to get the long time DateTime format but with fractional seconds.

I could of course get DateTimeFormatInfo.LongTimePattern and append ".fff" to it and pass it to the DateTime.ToString(), but some of the culture specific formats, US specifically, end with AM/PM. So it isn't that simple.

The second issue is that DateTime.ToString() does not appear to localize the number decimal separator. If I decided to just force each culture to use a hard coded custom time format it still will not create a localized string as the number decimal separator will not be culture specific.

To complicate matters further, some cultures have date time formats that use periods as part of their formatting. This makes it difficult to put a placeholder, for example the period and replace it with a culture specific decimal separator.

For now I have resorted to this workaround:

string format = string.Format("HH:mm:ss{0}fff",
    CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
string time = DateTime.Now.ToString(format);

Which I think should work for every culture that doesn't have the same decimal separator as the time separator, but that is an assumption.

Of Note: While it would be nice to have a solution to both issues, for my specific application I am more interested in localizing a custom date time format with fractional seconds than using a standard date time format.

like image 981
Joel McBeth Avatar asked Mar 20 '12 20:03

Joel McBeth


1 Answers

I think this will give you something close to what you require

var now = DateTime.Now;
var seconds = now.TimeOfDay.TotalSeconds % 60;
var timeText = string.Format(CultureInfo.GetCultureInfo("fr-FR"), 
                             "{0:d} {0:hh:mm:}{1:00.000}", now, seconds);

or just use

var timeText = string.Format(CultureInfo.CurrentCulture, 
                             "{0:d} {0:hh:mm:}{1:00.000}", now, seconds);

For example

  • fr-FR: 20/03/2012 10:20:10,088
  • en-GB: 20/03/2012 10:21:08.724
  • en-US: 3/20/2012 10:21:24.470
like image 138
Phil Avatar answered Sep 20 '22 10:09

Phil