I am trying to localize A.M. & P.M. in datetime in C#.
How reliable is it to use values returned by C#’s ‘PMDesignator’ & ‘AMDesignator’ (as in the code below) ?
How can I handle both the below scenarios using the same code?
//Line# Output
//----- ------
void Main() //1
{ //2
DateTime dt = DateTime.Now; // it is 5:56 PM now //3 it is 5:56 PM now
//4
//Japanese //5
var JapaneseCulture = new System.Globalization.CultureInfo("ja"); //6
Console.WriteLine(JapaneseCulture.DateTimeFormat.PMDesignator); //7 午後
Console.WriteLine(JapaneseCulture.DateTimeFormat.AMDesignator); //8 午前
Console.WriteLine(dt.ToString("t",JapaneseCulture)); //9 17:56
Console.WriteLine(dt.ToString("hh:mm tt",JapaneseCulture)); //10 05:56 午後
//11
//German //12
var GermanCulture = new System.Globalization.CultureInfo("de"); //13
Console.WriteLine(GermanCulture.DateTimeFormat.PMDesignator); //14 (blank)
Console.WriteLine(GermanCulture.DateTimeFormat.AMDesignator); //15 (blank)
Console.WriteLine(dt.ToString("t",GermanCulture)); //16 17:56
Console.WriteLine(dt.ToString("hh:mm tt",GermanCulture)); //17 05:56
}
Japanese –
PMDesignator, AMDesignator have values,
but are not shown in Line 9 when using “t”.
In this case the format specified in Line 10 (“hh:mm tt”) gives more correct output.
German –
PMDesignator, AMDesignator don’t have values,
so using “t” as in Line 16 gives the correct output,
while Line 17 which uses “hh:mm tt” gives incorrect output.
[EDIT: After reading comments:]
Does “t” give the “typically” used formats fairly reliably? (I have no prior experience in localization, so I do not have a good idea of how reliable the values are)
The Standard Date and Time Format Strings in .NET will do the correct thing for the user’s culture. In your case just use:
Only override the culture-specific format with customizations if really required by a specific business requirement.
Microsoft throws a lot of money at their localization efforts to ensure that formatting, translations, etc. are correct for everyone.