Search code examples
c#datetimeutc

Date Time Format is not Formatting


I need have this format : aaaa-mm-jjThh:mm:sszzzzzz

And put it in a XML property "DateTime" type.

So, I did it :

var xmlObj= new xmlObj.tHeader();
xmlObj.prop = DateTime.ParseExact(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"), "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);

Console.WriteLine(xmlObj.prop);

The Console.WriteLine instruction return : 03/05/2016 15:43:10

I don't understand why the property remove the format.

In the XSD, this property is waiting a datetime format.

Any ideas?

EDIT :

Ok, on the command result, I see a default format but If convert my XML object to File, the format is correct :

enter image description here

Very strange... but it's ok now. Many thanks to all of you


Solution

  • You are calling DateTime.ParseExact, which parses a string into a DateTime object. Just drop that part and assign the result of ToString directly to xmlObj.prop, or assign the DateTime object directly (if that's what it's looking for).

    Edit:

    To address your edit, your XML file is generated correctly. However, when you output the DateTime prop to the console, it uses the default string format for a date. You can format that with ToString() if you want to.