Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert DateTime .NET datatype to W3C XML DateTime data type string and back?

I have a System.DateTime object and I need to convert it into a string storing that datetime in W3C XML DateTime format (yyyy-mm-ddThh:mm:ssZ) and then be able to convert the resulting string back into System.DateTime.

Is there something ready for that in .NET or do I have to implement it myself?

like image 700
sharptooth Avatar asked Apr 15 '11 13:04

sharptooth


3 Answers

I thought W3C dateTime had a lot more significant digits for the time. Here's what I use:

// DateTime to W3C dateTime string string formatString= "yyyy-MM-ddTHH:mm:ss.fffffffzzz"; dateTimeField.ToString(formatString) ;  // W3C dateTime string to DateTime  System.Globalization.CultureInfo cInfo= new System.Globalization.CultureInfo("en-US", true); dateTimeField= System.DateTime.ParseExact(stringValue, formatString, cInfo); 
like image 193
Cheeso Avatar answered Oct 22 '22 13:10

Cheeso


If you want a date in the W3C XML format, then use .Net's W3C XML formatting API (been there since before v1.0):

var w3cStringFormat = XmlConvert.ToString(DateTime.Now);

results in:

2014-09-12T16:03:22.6833035+01:00

Then to get it back again:

var dateTime = XmlConvert.ToDateTime(w3cStringFormat);
like image 42
RichB Avatar answered Oct 22 '22 12:10

RichB


This will convert to the string you need and parse back the string to the DateTime:

var now = DateTime.Now;
Console.WriteLine(now.ToUniversalTime().ToString());
var nowString = now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(nowString);

var nowAgain = DateTime.ParseExact(nowString, "yyyy-MM-ddTHH:mm:ssZ", null);
Console.WriteLine(nowAgain.ToUniversalTime().ToString());

Console.ReadLine();
like image 29
Karg Avatar answered Oct 22 '22 13:10

Karg