My task is to retrieve data from XML file. Every node in XML file contains date and time. To read and convert it I'm using the following:
date = DateTime.ParseExact(turnoNode.SelectSingleNode("FechaHoraAlta").InnerText, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
For the first two nodes it converts dates correctly:
<FechaHoraAlta>19/04/2012 10:00:36</FechaHoraAlta>
<FechaHoraAlta>19/04/2012 11:00:05</FechaHoraAlta>
The problem occurs for the third node containing:
<FechaHoraAlta>22/04/2012 19:37:52</FechaHoraAlta>
Then FormatException exception is thrown saying that string was not recognized as a valid DateTime.
I tried to debug it, all I know is that it gets InnerText correctly, it's "22/04/2012 19:37:52". It just cannot convert it, but I have no idea why.
I saw a lot of similar problems here on stackoverflow, but so far I haven't found any proper solution.
Does someone know what the problem can be?
Thank you in advance.
Look at your format pattern:
"dd/MM/yyyy hh:mm:ss"
"hh" means a twelve hour clock, usually in conjunction with "tt" for the AM/PM designator. So 19 isn't a valid value. You want "HH" instead of "hh", as "HH" uses the 24 hour clock.
See MSDN on custom date and time format strings for more information.