views:

36

answers:

2

Hi,

I'm trying to convert an xmlattribute's value (yyyy-MM-ddTHH:mm:sszzzzzz) to yyyyMMdd.

I'm trying to use:

XmlConvert.ToDateTime(xmlattribute.Value, "yyyyMMdd")

But i'm getting formatexceptions:

"An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll"

Any help is very much appreciated... Thanks!

A: 

The ToDateTime returns a DateTime not a formatted string as you seem to want.

Try:-

 string formattedDate = ((DateTime)xmlattribute).ToString("yyyyMMdd");
AnthonyWJones
Thanks it works perfectly
Jamie
+1  A: 

You are getting the format exception because you are telling the formatter the string is "yyyyMMdd" but it is in fact "yyyy-MM-ddTHH:mm:sszzzzzz".

What you need to do is create a dateTime object using the value, then get a string back from the dateTime object in your desired format using the ToString(...) method. E.g.

  DateTime dateTime = XmlConvert.ToDateTime(xmlattribute.value);
  string result = dateTime.ToString("yyyyMMdd");

edit

According to the MSDN docs the XmlConvert.ToDateTime(string) method is depricated in favour of ToDateTime(String, XmlDateTimeSerializationMode). Docs are http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.todatetime.aspx

Suggest you try

    DateTime dateTime = XmlConvert.ToDateTime
        (xmlattribute.value, 
         XmlDateTimeSerializationMode.Unspecified);
Steve Haigh
Thanks for the quick reply but when i use the ToDateTime method i get the error: "No overload for method 'ToDateTime' takes 1 argument"
Jamie
Hmm. OK, I'll add an edit... not sure why you see this though, it *should* be supported.
Steve Haigh
Thanks, works fine. Also for another use i need to convert the DateTime string to be displayed as the long date etc. 20101030 into 30th october 2010, how would i do this? Thanks
Jamie
don't worry i worked it out for myself :)
Jamie
Cool:-) The MSDN docs for DateTime.ToString() should cover this.
Steve Haigh