我有一个简单的例程,它解析一个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?
发布于 2015-05-07 01:27:31
实际上,你不需要所有这些代码行。你只需要这个:
// 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子句中我们会记录这一点。
发布于 2015-05-07 01:28:09
你得试试这个:
string DateString = DateTime.Now.ToString("dd-MMM-yy");
string fileName = String.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
发布于 2015-05-07 01:37:10
您甚至不需要将DateTime.Now
转换为字符串,您可以使用String.Format一步创建整个字符串:
var fileName = String.Format("MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
或
var fileName = String.Format(CurrentInfo.InvariantCulture,
"MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
以避免国际化问题。
https://stackoverflow.com/questions/30096961
复制