当我们构建DateTimeFormatInfo时,它总是指定格式字符串,如果我们将其作为IFormatProvider传递给ToString或string.Format方法,它的日历也用于显示日期时间(由日历计算的日期元素)但是如果我们没有通过它,默认情况下,当前区域性信息作为IFormatProvider传递,因此当前区域性日历用于计算日期时间元素。在四种特殊情况下,不管您用于创建DateTimeFormatInfo或传递给这些方法的每个IFormatProvider的区域性如何,都使用了固定区域性和固定日历。"O" (or "o"), "R" (or "r"), "s", and "u"。下面的示例显示了一些示例:
static void ChangeStandardFormatStringAssociation()
{
// Build a writable instance of DateTimeFormatInfo which is get from writable CultureInfo (for example using ctor or using CreateSpecificCulture)
var formatInfo = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat; // d standard format associated by "MM-dd-yyyy" in short Date for en-US but we want to change it to "dd-MM-yyyy"
Console.WriteLine($"Culture which FormatInfo built from:en-US (This can not calculate from FormatInfo)");
Console.WriteLine($"FormatInfo is readonly?{formatInfo.IsReadOnly}");
Console.WriteLine(formatInfo.ShortDatePattern);
CultureInfo.CurrentCulture = new CultureInfo("fa-IR");
// What is current culture?
Console.WriteLine($"Current Culture is :{Thread.CurrentThread.CurrentCulture.Name}");
var dt = DateTime.Now.ToUniversalTime();
Console.WriteLine($"{dt:d} (Current Culture)");// consider that if we do not specify formatInfo it uses the current culture
Console.WriteLine($"{dt.ToString("d", formatInfo)} (Culture which formatInfo built from)"); // It uses Calendar related to that cultureInfo and then calculate parts of given date in that culture and shows them
Console.WriteLine($"{dt.ToString(formatInfo.ShortDatePattern)} (Culture which formatinfo build from Get the format string and calendar properties from current culture is used)");
Console.WriteLine($"{dt.ToString("r", CultureInfo.CurrentCulture)} (Invariant Culture and Invariant Calendar used Even we pass other culture info)");
Console.WriteLine($"{dt.ToString(formatInfo.ShortDatePattern, formatInfo)} (Culture which formatinfo build from Get the format string and calendar properties from that culture is also used since we set it as format provider)");
}
1条答案
按热度按时间bttbmeg01#
当我们构建
DateTimeFormatInfo
时,它总是指定格式字符串,如果我们将其作为IFormatProvider
传递给ToString
或string.Format
方法,它的日历也用于显示日期时间(由日历计算的日期元素)但是如果我们没有通过它,默认情况下,当前区域性信息作为IFormatProvider
传递,因此当前区域性日历用于计算日期时间元素。在四种特殊情况下,不管您用于创建DateTimeFormatInfo
或传递给这些方法的每个IFormatProvider
的区域性如何,都使用了固定区域性和固定日历。"O" (or "o"), "R" (or "r"), "s", and "u"
。下面的示例显示了一些示例: