0

I have the following string

\\server\f$\direct1\205486060518032015-05-28 150931.rtf

Which contains a date in the format yyyy-MM-dd hhmmss

Now I have managed to extract that string using a Regular Expression

Regex rgx = new Regex(@"\d{4}-\d{2}-\d{2} \d{6}");

di = new DirectoryInfo(Location);

var fileList = di.GetFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (FileInfo fi in fileList)
{
     EngineEvent(this, new EngineEventProperties(String.Format("Filename: {0}", fi.FullName)));
     DateTime fileDate = DateTime.Now;

     Match mat = rgx.Match(fi.FullName);
.
.
.

}

The Match contains the expected string '2015-05-28 150931'

However when I try and use the following code to convert it to a DateTime

if (DateTime.TryParseExact(fi.FullName, "yyyy-MM-dd hhmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out fileDate))
{
     Console.WriteLine("Date : {0}", fileDate);
};

It returns false, using ParseExact fails saying the string does not contain a date.

So how can I do the conversion?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Paul S Chapman
  • 832
  • 10
  • 37
  • possible duplicate of [C# DateTime to "YYYYMMDDHHMMSS" format](http://stackoverflow.com/questions/3025361/c-sharp-datetime-to-yyyymmddhhmmss-format) – SpYk3HH May 28 '15 at 16:24
  • 1
    I'm not sure we need to know how you get the date string? This questions boils down to *how do I turn this string into a date*. The other stuff is irrelevant. – Liam May 28 '15 at 16:24
  • possible duplicate of [Parse string to DateTime in C#](http://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – Liam May 28 '15 at 16:24
  • 3
    @Liam it's relevant because the OP is passing the wrong value to `ParseExact`. – D Stanley May 28 '15 at 16:29

2 Answers2

4

use this format:

"yyyy-MM-dd HHmmss"

HH is for 24 hour time format, hh is for 12 hour format. 15 doesn't fit in a 12 hour time format, hence the failure.

Give it a shot:

DateTime temp;
if (DateTime.TryParseExact("2015-05-28 150931", "yyyy-MM-dd HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
{
     Console.WriteLine("Date : {0}", temp);
};

always good to bookmark the Custom Date and Time Format Strings page!

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • Thanks - I had another error in the code in that I was using fi.filename when I should have been using mat.Value - but it was the format that was wrong so your suggestion was what I was missing. – Paul S Chapman May 28 '15 at 16:35
3

You're trying to parse the full name, not just the matched part. Try

Match mat = rgx.Match(fi.FullName);

if (mat.success)
{
    if (DateTime.TryParseExact(mat.Value, "yyyy-MM-dd HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out fileDate))
    {
         Console.WriteLine("Date : {0}", fileDate);
    };
}
else
{
    // no natch found...
}

Also changed the hour match to 24-hour (HH) as identified by @Jonesy

D Stanley
  • 149,601
  • 11
  • 178
  • 240