2012-03-13 62 views
1

在C#中,一个人如何使用DateTime格式字符串来控制显示,并在同一时间不能逾越的CultureInfo什么日期中的部分?格式化日期时间没有在C#重写的CultureInfo

System.Globalization.CultureInfo cultureInfoUS = new System.Globalization.CultureInfo("en-US", false); 
System.Globalization.CultureInfo cultureInfoGerman = new System.Globalization.CultureInfo("de-DE", false); 

System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoUS; 
DateTime date = DateTime.Parse("03-13-2012 01:30:00 PM"); 

Console.WriteLine(date.ToString(cultureInfoGerman)); 
//produces 13.03.2012 13:30:00 
Console.WriteLine(date.ToString("MM/dd/yyyy", cultureInfoGerman)); 
//produces 03.13.2012 but should be 13.03.2012 

System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoGerman; 
Console.WriteLine(date.ToShortTimeString()); 
//produces: 13:30 
Console.WriteLine(date.ToString("h:mm tt", cultureInfoGerman)); 
//produces: 1:30 but should be 13:30 
Console.WriteLine(date.ToString("h:mm tt", cultureInfoUS)); 
//produces: 1:30 PM 

您可以在上面的代码中看到注释。输出部分由CultureInfo部分调整,但不完全。

此外,ToShortDateStringToShortTimeString方法不需要IProvider,因此必须依赖当前线程的文化信息。上面的第一个例子说明了这一点。是你要改变当前的文化,叫ToShortDateString然后恢复线程回到原来的文化期待?

回答

0

我不明白,在你的代码中的注释 - 您使用的正是表现为我所期望的自定义​​日期/时间格式说明。为什么你会想到“MM/DD/YYYY”把天第一?

如果你想要的是基于一个特定的文化中使用的模式自定义格式,你可以通过查看DateTimeFormatInfo.ShortDatePatternDateTimeFormatInfo.ShortTimePattern等。例如,如果你想与随后一周的某一天自定义格式构建它特定的文化很短的时间,你可以使用:

string format = "dddd " + culture.DateTimeFormat.ShortTimePattern; 
Console.WriteLine(DateTime.Now.ToString(format, culture); 

是,你应该改变目前的文化,叫ToShortDateString然后恢复线程回到原来的文化期待?

不,你应该使用standard date/time format string如果你想比目前的文化以外的东西:“”

date.ToString("d", culture); // short date 
date.ToString("t", culture); // short time 
+1

我期待的真正原因更改了“/”变成一个并且DE小时数为1而不是13,并且AM/PM被丢弃。只要全球化的担忧仅限于基本的短日期和时间很短,我想我并不需要担心。答案似乎是格式字符串部分覆盖和CultureInfo的被部分覆盖。 – jedatu 2012-03-13 18:35:26