I\'m to get a custom DateTime format including the AM/PM designator, but I want the \"AM\" or \"PM\" to be lowercase without making the rest of of the characters lo
The problem with the above approaches is that the main reason you use a format string is to enable localization, and the approaches given so far would break for any country or culture that does not wish to include a final am or pm. So what I've done is written out an extension method that understands an additional format sequence 'TT' which signifies a lowercase am/pm. The below code is debugged for my cases, but may not yet be perfect:
///
/// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format. The format has extensions over C#s ordinary format string
///
/// this DateTime object
/// A DateTime format string, with special new abilities, such as TT being a lowercase version of 'tt'
/// A string representation of value of the current System.DateTime object as specified by format.
public static string ToStringEx(this DateTime dt, string formatex)
{
string ret;
if (!String.IsNullOrEmpty(formatex))
{
ret = "";
string[] formatParts = formatex.Split(new[] { "TT" }, StringSplitOptions.None);
for (int i = 0; i < formatParts.Length; i++)
{
if (i > 0)
{
//since 'TT' is being used as the seperator sequence, insert lowercase AM or PM as appropriate
ret += dt.ToString("tt").ToLower();
}
string formatPart = formatParts[i];
if (!String.IsNullOrEmpty(formatPart))
{
ret += dt.ToString(formatPart);
}
}
}
else
{
ret = dt.ToString(formatex);
}
return ret;
}