Tôi có một số tin xấu cho bạn. Khung không hỗ trợ định dạng bạn đang tìm kiếm. Mã sau đây chứng minh điều này:
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));
}
}
}
Ứng dụng hiển thị tất cả định dạng ngày giờ được hỗ trợ. Không ai trong số họ hỗ trợ khái niệm về 18:00 ==> 18 giờ, v.v.
Tùy chọn tốt nhất của bạn là viết phương pháp mở rộng hoặc phương pháp tương tự.
Văn hóa cách tiếp cận nhạy cảm: xây dựng một lớp mở rộng helper:
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();
}
}
}
Bạn có thể kiểm tra như sau:
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());
Mặc dù tôi là người Pháp Tôi không biết chúng tôi không đặt 00 –
Haha. @ GôTô có thể là một điều Canada của người Pháp? – Justin
Vâng, có thể tiếng Pháp của Canada thật kỳ lạ: P (đùa thôi!) –