Question

So this seems like an easy thing to do, but still has me stumped. I want to display a list of strings to my user, based off of a few file's creation dates. So basically, display a list of DateTimes. The challenge is that want to use a custom format (something like 5/6/13 12:01 PM) but I want he date part of that to display differently based on how you have your system displaying the date (ie. a Brit would display that date as 6/5/13).

I thought I could just build two strings (one for date and one for time) and make sure that they date is region-formatted, but there is no default option for 5/6/13 (only 5/6/2013): http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Next I hoped maybe the DateTime.ToShortDateString() function would work, but it displays as 5/6/2013 as well.

I know I can use a completely custom format like this: DateTime.ToString("M/d/yy h:mm tt") but I don't want to fix the date with the month before the day.

I suppose if I can' figure anything out then I could just build a custom datetime for America and for Europe and then query the OS for what datetime they are displaying in. But that seems really excessive. Any thoughts?

Was it helpful?

Solution 2

System.Globalization.CultureInfo implements IFormatProvider, so you can provide a CultureInfo object as a parameter to the ToString method.

MSDN seems to have an example of exactly what you want.

OTHER TIPS

You could retrieve the current ShortDate format from current culture, change it and use it with ToString()

var currentDate = DateTime.Now;
var shortDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
var newShortDateFormat = shortDateFormat.Replace("yyyy", "yy");
Console.WriteLine(currentDate.ToString(shortDateFormat));
Console.WriteLine(currentDate.ToString(newShortDateFormat));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top