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

我知道如何将 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/

相关文章:

html - html属性和值之间的空格?

vim - 如何在 Vim 中插入对齐文本列所需的可变数量的空格?

r - 用 R 定义 Excel 的列宽

intellij-idea - 如何阻止 IntelliJ IDEA 从 .properties 文

.net - 文化不可变对象(immutable对象) ToString()

algorithm - 需要一种算法来拆分一系列数字

netbeans - 更改netbeans中自动突出显示的变量名的突出显示颜色?

text - 为什么 LaTeX 会忽略文档类中的字体大小

string - 在包含花括号的字符串上使用 -f 运算符

sql-server - SQL Server 2008 : how to format the o