Search code examples
c#windows-phone-8

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"


I have a WP8 app, which will send the current time to a web service.

I get the datetime string by calling

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff")

For most users it works great and gives me the correct string like "09/10/2013 04:04:31.415". But for some user the resulted string is something like "09/14/2013 07.20.31.371", which causes problem in my web service.

Is it because some culture format issue? How can I make sure the result string is delimited by colon instead of dot?


Solution

  • Is it because some culture format issue?

    Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.

    How can I make sure the result string is delimited by colon instead of dot?

    I'd suggest specifying CultureInfo.InvariantCulture:

    string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                    CultureInfo.InvariantCulture);
    

    Alternatively, you could just quote the time and date separators:

    string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");
    

    ... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:

    using System;
    using System.Globalization;
    using System.Threading;
    
    class Test
    {
        static void Main()        
        {
            DateTime now = DateTime.Now;
            CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
            Thread.CurrentThread.CurrentCulture = culture;
            Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
        }
    } 
    

    That produces output (on September 18th 2013) of:

    11/12/1434 15:04:31.750
    

    My guess is that your web service would be surprised by that!

    I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:

    string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture);
    

    This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)