Picking the right DateTimePattern RRS feed

  • Question

  • My current setting displays a DateTime like this (en-GB):

    DateTime DT = DateTime.Now.ToString("F");

    Result: 22 November 2018 13:00:00

    Prob: it's missing the day name that I want.

    Using the DateTimeFormatInfo.GetAllDateTimePatterns('F'), I can see a few formats that have: dddd, dd MMMM YYYY

    and it will give me exactly what I want:

    Thursday, 22 November 2018 13:00:00

    However, this wanted pattern is one of another 10, some have the dddd, some do not. How can I select the best one that has dddd in it? I'm thinking of getting the first pattern that has the dddd in it (using string.contains()). Are they sorted in priority order?


    • Edited by David Tetard Thursday, November 22, 2018 3:25 PM
    Thursday, November 22, 2018 3:24 PM

All replies

  • Well, "F" is the full date/time pattern as defined in the systems settings. Thus if you don't get the day, this means your should change your systems settings:

    Thursday, November 22, 2018 4:20 PM
  • Ultimately it is up to you to decide which format you want. As defined here you have the option of a large number of predefined formats. You mentioned the "F" specifier and this does show the day of the week like you wanted. it depends upon the culture as to whether you get 12 or 24 hour time.

    //Thursday, November 22, 2018 14:12:10
    var longDateTime = dt.ToString("F");

    If none of pre-defined give you what you want then switch to the custom formatting options which allow you to mix and match in whatever format you need.

    //Thursday, November 22 2018 14:12:10
    var customFormat = dt.ToString("dddd, MMMM dd yyyy HH:mm:ss");

    Do note however that users are able to customize their date/time format in Windows. If you're building out a UI then you should honor their settings by simply using ToString or one of the variant methods. If the user wants 12/24-hour, short or long months, weekdays or no then it is their choice. Nothing is more infuriating then customizing your date/time format and then having an app show its own format anyway. Reserve custom formatting for back end systems where you require a specific format to work (e.g. databases, service calls, etc).

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 22, 2018 4:43 PM