inside
inside

Reputation: 3177

DateTime Format provider for filepath

I have a file-path that's been created from DateTime stamp:

"C:\\Logs\\Tests\\2015\\Mar\\24\\13_32_09\"

Now I am trying to convert my file-path back to DateTime object.

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.

Any example, may not be particular solution to my answer, would be helpful.

Thanks

Upvotes: 0

Views: 267

Answers (2)

Habib
Habib

Reputation: 223282

You can use DateTime.ParseExact like:

DateTime dt = DateTime.ParseExact("2015\\Mar\\24\\13_32_09\\", 
                                  @"yyyy\\MMM\\dd\\HH_mm_ss\\", 
                                  CultureInfo.InvariantCulture);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501976

No, you don't need to create an IFormatProvider at all. 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):

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. (You might want to canonicalize the directory separators first.)

Upvotes: 2

Related Questions