我知道如何将 DateTime
格式化为 String
。可能有很多方法可以将 DateTime
格式化为 String
,我发现很少有与 DateTime
格式相关的问题。
但我找到并尝试了两种方法:
GetDateTimeFormats()
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/