【问题标题】:Formatting a Date/Time in C#在 C# 中格式化日期/时间
【发布时间】:2011-11-12 12:39:35
【问题描述】:

我有一个如下所示的日期/时间字符串:

Wed Sep 21 2011 12:35 PM Pacific

如何将 DateTime 格式化为如下所示?

谢谢!

【问题讨论】:

标签: c# datetime formatting timezone


【解决方案1】:

查看有关 Custom Date and Time Format Strings 的文档。

【讨论】:

    【解决方案2】:

    时区前的位很简单,使用custom date and time format string

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

    但是,我相信 .NET 日期/时间格式不会为您提供“太平洋”部分。它可以为您提供的最佳信息是与 UTC 的时区偏移。如果您可以通过其他方式获取时区名称,那很好。

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

    【讨论】:

    • 给出 24 小时时间和 AM/PM 是不是有点多余? :P
    • +1,偏移量 -8 可能并不总是意味着太平洋 - 许多命名区域共享相同的偏移量,并且 DateTime/DateTimeOffset 不存储它。
    • @Brandon:是的,doh。当然,它可能仍然是 24 小时 - 我们无法确定。 (当然,星期几名称的格式已经存在冗余。)
    • @Paul:你是在向合唱团布道 :) 话虽如此,即使是野田时间也不会只有“太平洋”作为时区 ID...
    【解决方案3】:
    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 中运行此示例,然后在程序模式下运行它。

    更多编辑

    在下面的 cmets 之后,这是更新的版本。

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

    【讨论】:

    • 不需要同时混合 String.Format 和 ToString。您可以在一个电话中完成所有操作:String.Format("{0:ddd MMM dd yyyy HH:mm tt} {1}", DateTime.Now, TimeZone.CurrentTimeZone.StandardName)
    • 哦,哎呀。 HH 应该是 hh 12 小时时间。
    【解决方案4】:

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

    采纳并补充 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;
    

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

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      相关资源
      最近更新 更多