2011-09-07 96 views
4

我有一个日期/时间字符串,看起来像以下:格式化日期/时间在C#

Wed Sep 21 2011 12:35 PM Pacific 

我如何格式化一个DateTime到这个样子?

谢谢!

+1

我一直使用这个家伙的备忘单:http://blog.stevex.net/string-formatting-in-csharp/ –

+3

它总是*太平洋?因为我不相信.NET DateTime格式会为您提供时区*名称*。 –

回答

9

时区前位很容易,用custom date and time format string

string text = date.ToString("ddd MMM dd yyyy hh:mm t"); 

不过,我相信.NET日期/时间格式化会给你“太平洋”的一部分。它可以给你的最好的时区是,从UTC时间偏移。这很好,如果你能以其他方式获得时区名称。

许多TimeZoneInfo标识符包括字太平洋,但没有一个只是“太平洋”。

+1

给24小时和上午/下午不是多余的吗? :P – Brandon

+0

+1,偏移量-8可能并不总是太平洋 - 许多命名区域共享相同的偏移量,并且DateTime/DateTimeOffset不存储它。 –

+0

@布兰登:是的,呃。当然,它可能还是* 24 *小时 - 我们不能说。 (已经有格式的冗余,当然是星期几的名字。) –

6
string.Format("{0} {1}", DateTime.Now.ToString("ddd MMM dd yyyy HH:mm tt"), TimeZone.CurrentTimeZone.StandardName); 
//Result: Wed Sep 07 2011 14:29 PM Pacific Standard Time 

如果您不想显示标准时间,请关闭标准时间。

编辑: 如果您需要遍布整个地方,您还可以扩展日期时间以包含一个方法来为您完成此操作。

void Main() 
{ 
    Console.WriteLine(DateTime.Now.MyCustomToString()); 
} 

// Define other methods and classes here 
public static class DateTimeExtensions 
{ 
    public static string MyCustomToString(this DateTime dt) 
    { 
     return string.Format("{0} {1}", DateTime.Now.ToString("ddd MMM dd yyyy HH:mm tt"), TimeZone.CurrentTimeZone.StandardName).Replace(" Standard Time", string.Empty); 
    } 
} 

您可以在LinqPad中直接复制并粘贴并在程序模式下运行该示例。

更多修改

后从下面这是更新版本的意见。

void Main() 
{ 
    Console.WriteLine(DateTime.Now.MyCustomToString()); 
} 

// Define other methods and classes here 
public static class DateTimeExtensions 
{ 
    public static string MyCustomToString(this DateTime dt) 
    { 
     return string.Format("{0:ddd MMM dd yyyy hh:mm tt} {1}", DateTime.Now, TimeZone.CurrentTimeZone.StandardName).Replace(" Standard Time", string.Empty); 
    } 
} 
+1

有没有必要同时混合String.Format和ToString。您可以在一次调用中完成所有操作:'String.Format(“{0:ddd MMM dd yyyy HH:mm tt} {1}”,DateTime.Now,TimeZone.CurrentTimeZone.StandardName)' –

+0

哦,哎呀。 'HH'应该是'hh'12小时。 –

+0

是的,我更喜欢那个,谢谢。 –

2

请注意,这可能有点粗糙,但它可能会导致你在正确的方向。

以和添加到什么乔恩提到:

string text = date.ToString("ddd MMM dd yyyy hh:mm t"); 

然后沿着这些线路增加一些:

TimeZone localZone = TimeZone.CurrentTimeZone; 
    string x = localZone.StandardName.ToString(); 
    string split = x.Substring(0,7); 
    string text = date.ToString("ddd MMM dd yyyy hh:mm t") + " " + split; 

我没有测试过,但我希望它能帮助!