Search code examples
c#datetime-formatdate-conversion

How can I get a MediumDateString?


I can convert a string value in YYYYMMDD format to a human-friendlier string like so:

string beginDate = GetElement(3, fileBaseName);
string endDate = GetElement(4, fileBaseName);
beginDate = DateTime.ParseExact(beginDate,
    "yyyyMMdd",
    CultureInfo.InvariantCulture).ToShortDateString();
endDate = DateTime.ParseExact(endDate,
    "yyyyMMdd",
    CultureInfo.InvariantCulture).ToShortDateString();
return string.Format("{0} to {1}", beginDate, endDate);

But using ToShortDateString() as above, I get the not-as-friendly-as-desired format "4/1/2016 to 4/30/2016"

When I try ToLongDateString(), it goes too far the other direction, expanding the numbers into month names (which I want), but also providing the long form of the day of the week, so that the same values are displayed as "Friday, April 01, 2016 to Saturday, April 30, 2016"

What I really want is for the date range to be displayed as "April 1, 2016 to April 30, 2016" (or "April 1st, 2016 to April 30th, 2016")

Is there a middle ground between ToShortDateString() and ToLongDateString() that I can use, or will I need to "roll my own" to get this?


Solution

  • You can use your own custom format (MMMM d, yyyy):

    beginDate = DateTime.ParseExact(beginDate, 
                                    "yyyyMMdd", 
                                    CultureInfo.InvariantCulture)
                        .ToString("MMMM d, yyyy");
    
    
    endDate = DateTime.ParseExact(endDate, 
                                  "yyyyMMdd", 
                                  CultureInfo.InvariantCulture)
                        .ToString("MMMM d, yyyy");
    
    return string.Format("{0} to {1}", beginDate, endDate);
    

    Output:

    April 1, 2016 to April 30, 2016