我有一些坏消息要告诉你。该框架不支持您正在寻找的格式。下面的代码证明了这一点:
using System;
using System.Globalization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
// FR Canadian
Console.WriteLine("Displaying for: fr-CA");
DisplayDatesForCulture("fr-CA");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
// FR French
Console.WriteLine("Displaying for: fr-FR");
DisplayDatesForCulture("fr-FR");
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
static void DisplayDatesForCulture(string culture)
{
var ci = CultureInfo.GetCultureInfo(culture);
var dt = new DateTime(2010, 10, 8, 18, 0, 0);
foreach (string s in ci.DateTimeFormat.GetAllDateTimePatterns())
Console.WriteLine(dt.ToString(s));
}
}
}
该应用程序显示所有支持的日期时间格式。他们都不支持 18:00 ==> 18 小时等的概念。
您最好的选择是编写扩展方法或类似方法。
文化敏感的方法:构建一个扩展助手类:
public static class DateHelper
{
public static string ToLocalizedLongTimeString(this DateTime target)
{
return ToLocalizedLongTimeString(target, CultureInfo.CurrentCulture);
}
public static string ToLocalizedLongTimeString(this DateTime target,
CultureInfo ci)
{
// I'm only looking for fr-CA because the OP mentioned this
// is specific to fr-CA situations...
if (ci.Name == "fr-CA")
{
if (target.Minute == 0)
{
return target.ToString("H' h'");
}
else
{
return target.ToString("H' h 'mm");
}
}
else
{
return target.ToLongTimeString();
}
}
}
你可以像这样测试:
var dt = new DateTime(2010, 10, 8, 18, 0, 0);
// this line will return 18 h
Console.WriteLine(dt.ToLocalizedLongTimeString(CultureInfo.GetCultureInfo("fr-CA")));
// this line returns 6:00:00 PM
Console.WriteLine(dt.ToLocalizedLongTimeString());
var dt2 = new DateTime(2010, 10, 8, 18, 45, 0);
// this line will return 18 h 45
Console.WriteLine(dt2.ToLocalizedLongTimeString(CultureInfo.GetCultureInfo("fr-CA")));
// this line returns 6:45:00 PM
Console.WriteLine(dt2.ToLocalizedLongTimeString());