DateTimeFormatInfo string format for day of week. Thursday becomes Th
Is there a DateTimeFormatInfo
format pattern to convert a day of week to two characters? For example Tue开发者_Python百科sday becomes Tu, Wednesday becomes We. The format string needs to conform to the DateTimeFormatInfo
for date formats.
Addition:
Maybe I am looking for a solution to extend DateTimeFormatInfo
to include custom formats?
The closes you can get is the "ddd"
custom format specifier - this produces three lettered abbreviations, so not exactly what you want. There is nothing built in that does exactly what you want.
You can always take the first two characters of that:
DateTime.Now.ToString("ddd").Substring(0,2);
Unfortunately you can't extend DateTimeFormatInfo
since it is declared as sealed
.
You need to get the DateTimeFormatInfo
of the culture you're working with, then modify the array of strings called AbbreviatedDayNames
. After that, ddd
will return Th
for you.
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.abbreviateddaynames(VS.71).aspx
DateTimeFormatInfo.AbbreviatedDayNames
Gets or sets a one-dimensional array of type String containing the culture-specific abbreviated names of the days of the week.
Here's a sample of how to do it:
class Program
{
static void Main()
{
var dtInfo = new System.Globalization.DateTimeFormatInfo();
Console.WriteLine("Old array of abbreviated dates:");
var dt = DateTime.Today;
for (int i = 0; i < 7; i++)
{
Console.WriteLine(dt.AddDays(i).ToString("ddd", dtInfo));
}
// change the short weekday names array
var newWeekDays =
new string[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
dtInfo.AbbreviatedDayNames = newWeekDays;
Console.WriteLine("New array of abbreviated dates:");
for (int i = 0; i < 7; i++)
{
Console.WriteLine(dt.AddDays(i).ToString("ddd", dtInfo));
}
Console.ReadLine();
}
}
One more note: of course, if you are constrained from providing the IFormatProvider
, then you can override the current thread's CultureInfo
, for example:
CultureInfo customCulture = CultureInfo.CreateSpecificCulture("en-US");
// ... set up the DateTimeFormatInfo, etc...
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
More on CurrentCulture:
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx
Thread.CurrentUICulture Property
Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
To use the DateTimeFormatInfo specifically you can
dtfi.GetShortestDayName(DateTime.Now.DayOfWeek);
however "ddd" is the closest you'll get for a string format
try this
string s = DateVar.ToString("ddd").SubString(0,2);
If it needs to be a FormatPattern, then try this:
var dtFI = new CultureInfo( "en-US", false).DateTimeFormat;
dtFI.DayNames = new[] {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" };
string s = DateVar.ToString("ddd", dtFI);
精彩评论