c# - 我应该使用 ToString() 还是 GetDateTimeFormats() 来格式化 DateTime?

标签 c# .net datetime formatting string-formatting

我知道如何将 DateTime 格式化为 String。可能有很多方法可以将 DateTime 格式化为 String,我发现很少有与 DateTime 格式相关的问题。

但我找到并尝试了两种方法:

  1. GetDateTimeFormats()
  2. ToString("MM/dd/yyyy")

我试过这段代码:

public static class DateTimeFormates
{
    public static string FormatMyDate(this DateTime DT)
    {
        // My Actual Date Time Comes in this Format
        //8/23/2013 12:43:12 PM

        // I'm expecting Format like below

        String FormatWayOne = DT.GetDateTimeFormats()[3];
        //08/23/2013

        String FormatWayTwo = DT.ToString("MM/dd/yyyy");
        //08/23/2013

        return FormatWayOne;
    }
}

我有一个带有 Global 方法的 Global 类,可以将 DateTime 格式化为 String。但是在这里我想知道哪种方法是最佳实践以便我可以使用它?该方法在整个应用程序中被调用。

最佳答案

GetDateTimeFormats 不是 ToString 的替代品,反之亦然。如果您知道您想要什么格式,则无需调用 GetDateTimeFormats。除了使用 ToString 更清晰之外,document对于 GetDateTimeFormats 说明了这一点(强调我的)

Because this method uses culture-sensitive data, you should not assume that multiple calls to the method will return identical data. The data returned by this method can change if the current culture changes, the user overrides individual cultural settings, or an update occurs to the system's cultural data.

这可能会破坏您的代码,因为在另一种文化中运行时,第三个元素可能是别的东西。

通过使用 ToString,您可以避免遍历所有日期格式(因此效率更高),并且您可以更清楚地了解您喜欢的格式,同时确保返回的格式是您想要的格式。

关于c# - 我应该使用 ToString() 还是 GetDateTimeFormats() 来格式化 DateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18397327/

相关文章:

c# - 三层架构 - 如何将业务类(如 100 个属性)传递给数据访问

c# - 以异步方式编写类或仅异步调用它

c# - 套接字自动关闭

linux - 如何将字符串转换为特定格式的日期时间?

c# - C# .Net Office 365 API 入门

c# - 哪些 SQLite.Net.Attributes 忽略对象字段作为列?

c# - Entity Framework 通过单个插入添加多个相关实体

.net - 可移植类库和.NET ConcurrentDictionary

python - 使用箭头从带有时区的字符串中解析日期和时间

c++ - 如何将 C++ time_t 对象设置为纪元?