tomet
tomet

Reputation: 2556

Convert string to DateTime with Convert.ToDateTime

I'm a but frustrated. I'm playing around with xml-files. So this is my automatically created xml-File:

<Files>
<Lists>
    <oList>
      <Object>
        <Name>test1</Name>
        <DateCreated>2/11/2013 4:35:05 PM</DateCreated>
        <DateDeadline>2/17/2013 12:00:00 AM</DateDeadline>
        <Reward>none</Reward>
        <Description>chocolate amedei 9</Description>
      </Object>
    </oList>
  </Lists>
</Files>

The many start elements in the beginning have to be there because I want to extend the file later. So now I want to read this xml-file and create an object of a class (ThingsToDoObjects, it's supposed to become a to-do-list some day) that needs exactly the parameters stored in the xml-file. This Object should be stored in a list. So this is what I have so far:

XmlDocument xmlListDoc = new XmlDocument();
            xmlListDoc.Load(xmlFilePath);
            foreach (XmlNode xnode in xmlListDoc.SelectNodes("Files/Lists/oList/Object"))
            {
                string n = xnode.SelectSingleNode("Name").InnerText.ToString();
                DateTime c = Convert.ToDateTime(xnode.SelectSingleNode("DateCreated").InnerText.ToString());
                DateTime d = Convert.ToDateTime(xnode.SelectSingleNode("DateDeadline").InnerText.ToString());

                string r = xnode.SelectSingleNode("Reward").InnerText.ToString();
                string de = xnode.SelectSingleNode("Description").InnerText.ToString();
                ThingsToDoObjects NeuObject = new ThingsToDoObjects(n, c, d, r, de);
                o.Add(NeuObject);
            }

Now when I debug the following happens: n is created fine, c is created fine. But d just doesn't work.It gives an error:

"The string was not recognized as a valid DateTime"

(That's my translation from German, so maybe the error might be called a bit different. What's going on there? I hope I just made some stupid mistake.

By the way: I tried the ParseExactly() method but it dind't work either and gave the same error.

Thanks in advance to everone who answers.

Upvotes: 2

Views: 4585

Answers (3)

gislikonrad
gislikonrad

Reputation: 3571

Since you mentioned translating from German, I'm going to assume that you're in Germany. You're probably trying to parse the date as "you". What I mean is that the date is being parsed using the German culture formatter (dd/mm/yyyy) and there is no 17th month to parse to.

Try using this instead:

Convert.ToDateTime(value, CultureInfo.InvariantCulture.DateTimeFormat);

Upvotes: 1

dtb
dtb

Reputation: 217263

There is a standard way to format date/time values in XML:

<DateCreated>2013-11-02T04:35:05</DateCreated>

You can parse this format using the XmlConvert.ToDateTime Method:

DateTime result = XmlConvert.ToDateTime("2013-11-02T04:35:05",
                                        XmlDateTimeSerializationMode.Utc);

Or, better yet, have a look at LINQ-to-XML and use the XElement to DateTime Explicit Conversion:

DateTime result = (DateTime)obj.Element("DateCreated");

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500225

(I'm assuming you can't change the XML format itself. It would be much better to use a standard format, as suggested by dtb.)

If you've got text in a known format, use DateTime.ParseExact or DateTime.TryParseExact. They will work, if you give them the right format. I usually use the invariant culture for parsing in these cases too - you don't want a user culture's date separators etc to mess things up. In this case, it looks like the format string you want is "M/d/yyyy h:mm:ss tt".

Sample code:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        string text = "2/17/2013 12:00:00 AM";
        string format = "M/d/yyyy h:mm:ss tt";
        DateTime value = DateTime.ParseExact(text, format,
                                             CultureInfo.InvariantCulture,
                                             DateTimeStyles.None);
        Console.WriteLine(value);
    }
}

I'd also strongly suggest using LINQ to XML if you can. It'll make your XML handling a lot simpler than your current code.

Upvotes: 4

Related Questions