Search code examples
c#datedatetimestring-formattingdate-conversion

DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") gives different formats for different users


I assumed that ToString("yyyy/MM/dd HH:mm:ss") will force the string to be formatted with '/', but I can see that every device gets different formats. How can I force it to be saved with '/'?

Good example-

  • 2021/10/06 18:05:53

Strange examples I see in my DB from different users-

  • 2021-10-06 23:48:37

  • 2021.10.12 12:41:42

  • 2021. 10. 06 19:17:23 ('.'+ space after)

  • 2021.10.13 19.18.16

One solution is to replace every -, . and . to /, but this only solves the strange examples I found. What if there are others?


Solution

  • / in a format string means "the culture-specific date separator". If you want the literal forward-slash, quote it (and the colons, to avoid the use of a custom time separator):

    ToString("yyyy'/'MM'/'dd HH':'mm':'ss")
    

    Alternatively - and probably better - use the invariant culture. Not only will that use / as the date separator, but you won't need to worry about a culture having a different default calendar. (It'll always use the Gregorian calendar, which is presumably what you want.)

    Even better, use an ISO-8601 format - you're already using a "slightly unusual for humans" format of year-first, so you might as well go the whole hog and go with the standard format for dates and times.

    Sample code:

    String text = dateTimeValue.ToString(
        "yyyy-MM-dd'T'HH:mm:ss",
        CultureInfo.InvariantCulture);
    

    This is also the sortable standard date/time format so you can simplify the code significantly:

    String text = dateTimeValue.ToString("s");
    

    (That format always uses the invariant culture.)

    That's if you really need to format the string at all, though. If you're saving it in a database, I'd advise you to:

    • Use an appropriate type in the database, e.g. DATETIME
    • Store it using a parameter (specifying the value just as a DateTime), not formatted text

    If you do both of these, you'll avoid oddities like this.