我有一个简单的例程,它解析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);
Run Code Online (Sandbox Code Playgroud)
这是结果输出字符串:
MyArticle_Africa_07-May-15.PNG
Run Code Online (Sandbox Code Playgroud)
这一切都很好,直到我在美国机器上获得日期时间设置不同的用户,例如
15年5月7日
在这种情况下,我的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");
Run Code Online (Sandbox Code Playgroud)
此外,DateTime.ParseExact当我们想要获得您提到的此异常时,我们使用该方法.说这个,我的意思是我们知道我们要解析的日期的字符串表示具有确切的格式,我们已经指定了 DateTime.ParseExact,如果其中一些不是,我们不会被告知知道它.通常,我们会有一个try catch子句,在catch子句中我们会记录下来.