1

I am wanting to display a list of dates in a WPF app in short date format with padded days and months.

i.e. in Australia/UK, this should appear as dd/MM/yyyy. In the US it would appears as MM/dd/yyyy

Is there a culture sensitive straightforward/simple method or pattern I can use to do this?

 DateTime.ToShortDateString() 

does not pad the day and month.

3
  • what do you mean by padding?
    – d.moncada
    Jun 24, 2014 at 23:47
  • the format dd will pad the date with a "0" if it is only a single digit. i.e. the first of November in Australia will be 01/11 instead of 1/11
    – hitch
    Jun 25, 2014 at 0:39
  • It appears Jon Skeet addresses a similar issue here: stackoverflow.com/questions/9006806/…
    – hitch
    Jun 25, 2014 at 0:40

2 Answers 2

1

The CultureInfo is built into .NET framework so that you do not have to concern yourself with the details of formatting dates for each culture. So you should just do DateTime.ToShortDateString() and be done with it.

That being said, we can modify the CultureInfo ShortDatePattern to get what you want.

static void Main()
{
    DateTime date = new DateTime(2014, 1, 2);

    // Change our CuurentCulture to: US
    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-us");

    // Standard format for US: 1/2/2014
    Console.WriteLine(date.ToString("d"));        

    // Force leading zero on month and day for US format: 01/02/2014
    Console.WriteLine(GetShortDateString(date));



    // Change our CuurentCulture to: AU
    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-au");

    // Standard format for AU: 2/01/2014
    Console.WriteLine(date.ToString("d"));

    // Force leading zero on day for AU format: 02/01/2014
    Console.WriteLine(GetShortDateString(date));        
}

static string GetShortDateString(DateTime date)
{
    string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

    if (!format.Contains("dd"))
        format = format.Replace("d", "dd");

    if (!format.Contains("MM"))
        format = format.Replace("M", "MM");

    return date.ToString(format);
}
1
  • As always I just came up with a similar answer. Was going to go with: dt.ToString(d.ShortDatePattern.Replace("dd", "d").Replace("d", "dd").Replace("MM", "M").Replace("M", "MM"))) Thanks for your help.
    – hitch
    Jun 25, 2014 at 0:48
1

Have a look at the DateTimeFormatInfo class which formats DateTime values depending on culture.

1
  • I can't see anything methods or properties on this class that will help me format the string as I've specified. Can you please provide more information?
    – hitch
    Jun 25, 2014 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.