当前文化定义为从日期时间使用12或24小时格式获取的一天就在小时 [英] Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture
本文介绍了当前文化定义为从日期时间使用12或24小时格式获取的一天就在小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
NET有内置的ToShortTimeString()函数,日期时间使用该CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern格式。它返回像这样为EN-US:下午5点。对于24小时的培养,如去DE它会返回17:00。
我要的是与每一种文化工作的方式,只是仅返回小时(因此,下午5点,并在上述情况下,17)。什么是做到这一点的最好的/干净的方式?
谢谢!
解决方案
//显示15,因为我现在的文化是EN-GB
Console.WriteLine(DateTime.Now.ToHourString());
//显示下午3时
Console.WriteLine(DateTime.Now.ToHourString(新的CultureInfo(EN-US)));
//显示15
Console.WriteLine(DateTime.Now.ToHourString(新的CultureInfo(去DE)));
// ...
公共静态类DateTimeExtensions
{
公共静态字符串ToHourString(这个日期时间DT)
{
返回dt.ToHourString(空);
}
公共静态字符串ToHourString(这个日期时间DT,的IFormatProvider提供商)
{
的DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(供应商);
字符串格式= Regex.Replace(dtfi.ShortTimePattern,@[^ HHT \ S],);
格式= Regex.Replace(格式,@\ S +,).Trim();
如果(format.Length == 0)
返回 ;
如果(format.Length == 1)
格式='%'+格式;
返回dt.ToString(格式,dtfi);
}
}
.Net has the built in ToShortTimeString() function for DateTime that uses the CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern format. It returns something like this for en-US: "5:00 pm". For a 24 hour culture such as de-DE it would return "17:00".
What I want is a way to just return just the hour (So "5 pm" and "17" in the cases above) that works with every culture. What's the best/cleanest way to do this?
Thanks!
解决方案
// displays "15" because my current culture is en-GB
Console.WriteLine(DateTime.Now.ToHourString());
// displays "3 pm"
Console.WriteLine(DateTime.Now.ToHourString(new CultureInfo("en-US")));
// displays "15"
Console.WriteLine(DateTime.Now.ToHourString(new CultureInfo("de-DE")));
// ...
public static class DateTimeExtensions
{
public static string ToHourString(this DateTime dt)
{
return dt.ToHourString(null);
}
public static string ToHourString(this DateTime dt, IFormatProvider provider)
{
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider);
string format = Regex.Replace(dtfi.ShortTimePattern, @"[^hHt\s]", "");
format = Regex.Replace(format, @"\s+", " ").Trim();
if (format.Length == 0)
return "";
if (format.Length == 1)
format = '%' + format;
return dt.ToString(format, dtfi);
}
}
这篇关于当前文化定义为从日期时间使用12或24小时格式获取的一天就在小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文