Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 'DateTime.ToString()' to output the same string as an XML serialization of a 'DateTime'

Is there a standard DateTime format for use in C# that can be used with the ToString method that will produce the same format that is produced when you serialize a DateTime to XML?

For example: 2013-03-20T13:32:45.5316112Z

like image 250
user1450877 Avatar asked Apr 30 '13 09:04

user1450877


2 Answers

I think you have to be specific:

dateTime.ToString(“yyyy-MM-ddTHH:mm:ss.fffffffZ”);

You have to be careful about using the right time zone. See here for more details.

like image 123
Matthew Watson Avatar answered Sep 16 '22 12:09

Matthew Watson


Look here:

http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#UniversalFull

The format you want is:

myDate.ToString("u");

Example:

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToUniversalTime().ToString("u"));
// Displays 2008-04-10 13:30:00Z           

However, this is not quite what you're after (though probably would still work), therefore you may have to use a custom format:

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
// Displays 2008-04-10T13:30:00.000000Z           
like image 31
KaraokeStu Avatar answered Sep 18 '22 12:09

KaraokeStu