错误的日期时间格式

Wrong DateTime format

当我 运行 DotNetFiddle 中的以下代码时,我得到了我期望的输出:

var myDate = new DateTime(2019, 6, 1);
Console.WriteLine(myDate.ToString("MM/dd/yy")); 

// Output is: 06/01/19

但是当我 运行 在全新的 C# 控制台应用程序 (.NET Framework 4.5.2) 或 C# Interactive window 中使用完全相同的代码时,我得到了这个输出:

06-01-19

为什么控制台应用程序和 C# Interactive window 将输出中的 / 替换为 -?基于 this answer and the documentation,我希望日期用 / 而不是 - 分隔。在 Microsoft 文档的这个示例中,它显示包含 /:

的输出
Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", 
                   thisDate2); 
// The example displays the following output:
//    The current date and time: 06/10/11 15:24:16 +00:00

使用日期时间格式字符串时,/ 字符很特殊,就像 dMy 一样。这意味着使用 system-defined date separator character

因此 DotNetFiddle 的系统日期分隔符是 /,但您系统上的分隔符是 -

如果您真的总是需要 / 字符,链接文档中的这段摘录将有所帮助:

To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator.

注意这一点。 Over-riding 系统和用户的选择不能掉以轻心。例如,我有时看到人们想要这样做以便格式化日期以用于 SQL 命令,那就是 never 好吧;如果您将日期格式化为 SQL 的字符串,而不是使用查询参数,那您就大错特错了。