Io personalmente formattare in due parti: la parte non-am/pm, e la parte AM/PM con ToLower:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
item.PostedOn.ToString("tt").ToLower();
Un'altra opzione (che studieremo in un secondo) è per prendere il DateTimeFormatInfo corrente, creare una copia e impostare i designatori am/pm nella versione minuscola. Quindi utilizzare le informazioni sul formato per la normale formattazione. Vorresti memorizzare il DateTimeFormatInfo, ovviamente ...
EDIT: Nonostante il mio commento, ho comunque scritto il bit di caching. Probabilmente non sarà più veloce rispetto al codice di cui sopra (in quanto comporta una serratura e una consultazione dei dizionari), ma non rendere il codice chiamante più semplice:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
Ecco un programma completo per dimostrare:
using System;
using System.Collections.Generic;
using System.Globalization;
public class Test
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
}
private static readonly Dictionary<DateTimeFormatInfo,DateTimeFormatInfo> cache =
new Dictionary<DateTimeFormatInfo,DateTimeFormatInfo>();
private static object cacheLock = new object();
public static DateTimeFormatInfo GetLowerCaseInfo()
{
DateTimeFormatInfo current = CultureInfo.CurrentCulture.DateTimeFormat;
lock (cacheLock)
{
DateTimeFormatInfo ret;
if (!cache.TryGetValue(current, out ret))
{
ret = (DateTimeFormatInfo) current.Clone();
ret.AMDesignator = ret.AMDesignator.ToLower();
ret.PMDesignator = ret.PMDesignator.ToLower();
cache[current] = ret;
}
return ret;
}
}
}
fonte
2009-01-31 19:39:40
Maggiori informazioni presso http://stackoverflow.com/questions/448634/how-to-format-a-datetime-like-oct-10-2008-1043am-cst-in-c – tvanfosson