[英]DateTime Format provider for filepath
I have a file-path that's been created from DateTime stamp: 我有一个从DateTime戳创建的文件路径:
"C:\\Logs\\Tests\\2015\\Mar\\24\\13_32_09\"
Now I am trying to convert my file-path back to DateTime object. 现在,我试图将文件路径转换回DateTime对象。
With Regex I can easily remove "C:\\\\Logs\\\\Tests\\"
, but now I am assume I need to provide implementation of IFormtProvider to convert 2015\\\\Mar\\\\24\\\\13_32_09\\
into a DateTime object, but I haven't come along any similar example of how that's usually done. 使用Regex,我可以轻松删除
"C:\\\\Logs\\\\Tests\\"
,但是现在我假设我需要提供IFormtProvider的实现,以将2015\\\\Mar\\\\24\\\\13_32_09\\
转换为DateTime对象,但是我还没有出现任何类似的示例,说明通常是如何完成的。
Any example, may not be particular solution to my answer, would be helpful. 任何示例,可能不是我的答案的特定解决方案,都将有所帮助。
Thanks 谢谢
No, you don't need to create an IFormatProvider
at all. 不,您根本不需要创建
IFormatProvider
。 The invariant culture is fine for this (assuming the month name is always in English). 不变的文化对此很好(假设月份名称始终为英语)。 You can just use
DateTime.ParseExact
, passing in the appropriate custom format string (quoting the literal characters, either with apostrophes around them or backslashes before them): 您可以只使用
DateTime.ParseExact
,传入适当的自定义格式字符串 (引用文字字符,在其周围加上撇号或在其前面加反斜杠):
var dateTime = DateTime.ParseExact(
text,
@"yyyy'\'MMM'\'dd'\'HH'_'mm'_'ss'\'",
CultureInfo.InvariantCulture);
Note that this assumes the path really does use backslashes... it won't work on Unix as-is. 注意,这里假设路径确实使用反斜杠......它不会在Unix工作原样。 (You might want to canonicalize the directory separators first.)
(您可能想首先规范化目录分隔符。)
You can use DateTime.ParseExact
like: 您可以像这样使用
DateTime.ParseExact
:
DateTime dt = DateTime.ParseExact("2015\\Mar\\24\\13_32_09\\",
@"yyyy\\MMM\\dd\\HH_mm_ss\\",
CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.