C#DateTime ToString标准区域性格式 [英] C# DateTime ToString Standard culture format
问题描述
我可以为特定区域性更改DateTime的标准输出格式吗?示例:
Can I alter the standard output format of a DateTime for a specific culture. Example:
class Program
{
static void Main(string[] args)
{
PrintCultureDateTime("ca-ES");
PrintCultureDateTime("es-ES");
PrintCultureDateTime("en-US");
PrintCultureDateTime("en-GB");
PrintCultureDateTime("pt-PT");
}
public static void PrintCultureDateTime(string culture)
{
string result = new DateTime(2017, 10, 1).ToString("d",
CultureInfo.GetCultureInfo(culture));
Console.WriteLine(string.Format("{0}: {1}", culture, result));
}
}
输出:
ca-ES: 1/10/2017
es-ES: 01/10/2017
en-US: 10/1/2017
en-GB: 01/10/2017
pt-PT: 01/10/2017
我想要的是使用标准的 d格式或其他标准的格式在日期和月份中使用两位数字,以便固定DateTime字符串的大小。类似于这样的输出:
What I want is to use two digits for day and month using standard "d" format or another standartd one, in order to fix the size of DateTime strings . Something like that output:
ca-ES: 01/10/2017
es-ES: 01/10/2017
en-US: 10/01/2017
en-GB: 01/10/2017
pt-PT: 01/10/2017
推荐答案
基于@Jon Skeet的答案我已经实现了以下解决方案。我认为必须存在一次迭代的更好的正则表达式替换指令,但我没有更多时间来找到它。
Basing on @Jon Skeet answer I've implemented the following solution. I think that a better regular expression replacement instruction with a single iteration must exist but I've no more time to find it.
它不适用于格式'Year:'yyyy'; Month:'MM';'Day:'dd,但我将假设为错误。
It didn't works on format "'Year:' yyyy '; Month: ' MM '; 'Day: 'dd" but I' ll assume the "error".
public static void PrintCultureDateTime(string culture)
{
string result = new DateTime(2017, 10, 1).ToString(FixedSizeShortDatePattern(culture));
Console.WriteLine(string.Format("{0}: {1}", culture, result));
}
public static string FixedSizeShortDatePattern(string culture)
{
var cultureInfo = CultureInfo.GetCultureInfo(culture);
string format = cultureInfo.DateTimeFormat.ShortDatePattern;
return ReplaceSingleChar(ReplaceSingleChar(format, 'd'), 'M');
}
public static string ReplaceSingleChar(string input, char c)
{
string cStr = c.ToString();
string strRegex = string.Format(@"^({0})[^{0}]|[^{0}]({0})[^{0}]|[^{0}]({0})$", cStr);
return Regex.Replace(input, strRegex, (match) =>
{
string token = match.Groups[0].Value;
if (!string.IsNullOrEmpty(token))
{
return match.Value.Replace(cStr, string.Concat(cStr, cStr));
}
return token;
});
}
这篇关于C#DateTime ToString标准区域性格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!