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?
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);
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With