gpt4 book ai didi

c# - DateTime.ToString 从所有格式到 dd/MM/YYYY?

转载 作者:行者123 更新时间:2023-11-30 19:15:59 24 4
gpt4 key购买 nike

我有一个简单的例程,它解析 DateTime.Now 并对其执行 .ToString() 以将其添加到要保存的文件名中:

 DateTime timeNow = DateTime.Now;
string dateNow = timeNow.ToShortDateString();
DateTime dateTime = DateTime.ParseExact(dateNow, "dd/MM/yyyy", CultureInfo.InvariantCulture);
string DateString = dateTime.ToString("dd-MMM-yy");
string fileName = string.Concat("MyArticle_" + region + "_" + DateString + fileExtension);

这是生成的输出字符串:

MyArticle_Africa_07-May-15.PNG

这一切都很好,直到我在 DateTime 设置不同的美国机器上找到用户,例如

05-07-15

在这种情况下,我的 ParseExact() 方法抛出异常,因为输入不是有效的日期时间。有没有办法容纳所有日期时间输入并解析为 dd/MM/YYYY?

最佳答案

实际上,您不需要所有这些代码行。你只需要这个:

 // We just have to pass to the ToString
// method the exact format we want. Under the hood the CLR has
// the know how to execute this command and you get the desired
// output.
string DateString = DateTime.Now.ToString("dd-MMM-yy");

此外,当我们想要获取您提到的这个异常时,我们使用DateTime.ParseExact 方法。这么说,我的意思是我们知道我们想要解析的日期的字符串表示形式是我们在 DateTime.ParseExact 中指定的确切格式,如果其中一些不是我们想要的'被告知知道它。通常,我们会有一个 try catch 子句,并在 catch 子句中记录它。

关于c# - DateTime.ToString 从所有格式到 dd/MM/YYYY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30096961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com