在c#中格式化日期/时间

本文关键字:时间 日期 格式化 | 更新日期: 2023-09-27 18:07:50

我有一个日期/时间字符串,看起来像这样:

Wed Sep 21 2011 12:35 PM Pacific

我如何格式化一个日期时间看起来像这样?

谢谢!

在c#中格式化日期/时间

时区前的位很容易,使用自定义日期和时间格式字符串:

string text = date.ToString("ddd MMM dd yyyy hh:mm t");
然而,我相信。net日期/时间格式将不会给你"太平洋"部分。它能给你的最好的是时区与UTC的偏移。如果您可以通过其他方式获得时区名称,则可以这样做。

许多TimeZoneInfo标识符包括 Pacific这个词,但没有一个是"Pacific"。

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

如果您不想显示标准时间,请将其修剪掉。

编辑:

如果你需要在所有地方都这样做,你也可以扩展DateTime来包含一个方法来为你做这件事。

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);
    }
}

查看自定义日期和时间格式字符串的文档

注意,这可能有点粗糙,但它可能会引导您朝着正确的方向前进。

接受并补充Jon所提到的内容:

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;

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