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

标签 c# .net datetime

我有一个简单的例程,它解析 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/

相关文章:

Java 时区在运行时更改

c# - 用 SQL 语句的结果填充任何 ArrayList

c# - 与 C# 中的 block 等效?

python - 从日期时间字符串中检索数据和时间

c# - 如何使用 ABCPdf.NET 从 PDF 文件的所有页面中提取文本?

c# - 如何将 JSON 值映射到不同名称的模型属性

php - 当前日期和存储在数据库中的日期之间的差异不起作用

c# - 遍历嵌套的 XML 节点

c# - WinForms 和事件处理程序

c# - 在 Mono 中捕获窗口或小部件的图像