Problem with using DateTime.ParseExact with a text string in the format "WyyyyMMdd"

44 Views Asked by At

I am trying to parse into a string:

DateTime datWeekDB = DateTime.ParseExact(weekDB.Value, "WyyyyMMdd", CultureInfo.InvariantCulture);

The text strings are like, eg:

W20220120

But this is failing:

  <LogEntry Date="2022-01-20 14:51:09" Severity="Exception" Source="MSAToolsLibrary.Importer.Importer.ImportHistoryFromGeneric" ThreadId="1">
    <Exception Type="System.FormatException" Source="MSAToolsLibrary.Importer.Importer.AddWeekToHistory">
      <Message>String was not recognized as a valid DateTime.</Message>
      <StackTrace>   at MSAToolsLibrary.Importer.Importer.AddWeekToHistory(XDocument&amp; xdoc, MSAHistoryWeek historyWeek, DetectStudentItemDescriptionAndTypeDelegate funcDetectStudentItemDescriptionAndType, Boolean bSort) in D:\My Programs\2022\MSAToolsLibrary\MSAToolsLibrary\Importer\Importer.cs:line 275
   at MSAToolsLibrary.Importer.Importer.ImportHistoryFromGeneric() in D:\My Programs\2022\MSAToolsLibrary\MSAToolsLibrary\Importer\Importer.cs:line 146</StackTrace>
    </Exception>
  </LogEntry>

The first character W is fixed and will always precede the YYYYMMDD text. How do I circumnavigate this issue?

I have tried to research the correct use of this API call for when there is generic text in the format string. But not spotted anything.


Update

I will most likely rephrase the question. Since in the comments they stated that it should work, I thought I would confirm the actual text being passed in to parse. I have thie XElement variable called weekDB which I try to get the node name from:

DateTime datWeekDB = DateTime.ParseExact(weekDB.Value, "WyyyyMMdd", CultureInfo.InvariantCulture);

I make the call weekDB.Value but it is returning a concatenated string of all the inner text values. I was hoping it would return the name of the actual XElement node. How do I fix that?

0

There are 0 best solutions below