How can I get date and time formats based on Culture Info?
You can retrieve the format strings from the CultureInfo
DateTimeFormat
property, which is a DateTimeFormatInfo
instance. This in turn has properties like ShortDatePattern
and ShortTimePattern
, containing the format strings:
CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;
CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;
If you simply want to format the date/time using the CultureInfo
, pass it in as your IFormatter
when converting the DateTime
to a string, using the ToString
method:
string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));
// Try this may help
string us = DateTime.Now.Date.ToString("MM/dd/yyyy",new CultureInfo("en-US"));
or
string us = DateTime.Now.Date.ToString("dd/MM/yyyy",new CultureInfo("en-GB"));
You could take a look at the DateTimeFormat property which contains the culture specific formats.
Use a CultureInfo like this, from MSDN:
// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");
// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));
More info on MSDN. Here is a link of all different cultures.
Try setting a custom CultureInfo
for CurrentCulture
and CurrentUICulture
:
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));