<p>How do I convert a DateTime structure to its equivalent <a href="http://www.ietf.org/rfc/rfc3339.txt" rel="noreferrer">RFC 3339</a> formatted string representation and/or parse this string representation back to a <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> structure? The RFC-3339 date-time format is used in a number of specifications such as the <a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs" rel="noreferrer">Atom Syndication Format</a>.</p>

[{'answer_id': 17021, 'author': 'Oppositional', 'author_id': 2029, 'author_profile': 'https://Stackoverflow.com/users/2029', 'pm_score': 6, 'selected': True, 'text': '<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).</p>\n\n<pre><code>using System;\nusing System.Globalization;\n\nnamespace DateTimeConsoleApplication\n{\n    /// &lt;summary&gt;\n    /// Provides methods for converting &lt;see cref="DateTime"/&gt; structures to and from the equivalent RFC 3339 string representation.\n    /// &lt;/summary&gt;\n    public static class Rfc3339DateTime\n    {\n        //============================================================\n        //  Private members\n        //============================================================\n        #region Private Members\n        /// &lt;summary&gt;\n        /// Private member to hold array of formats that RFC 3339 date-time representations conform to.\n        /// &lt;/summary&gt;\n        private static string[] formats = new string[0];\n        /// &lt;summary&gt;\n        /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.\n        /// &lt;/summary&gt;\n        private const string format = "yyyy-MM-dd\'T\'HH:mm:ss.fffK";\n        #endregion\n\n        //============================================================\n        //  Public Properties\n        //============================================================\n        #region Rfc3339DateTimeFormat\n        /// &lt;summary&gt;\n        /// Gets the custom format specifier that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 3339 format.\n        /// &lt;/summary&gt;\n        /// &lt;value&gt;A &lt;i&gt;DateTime format string&lt;/i&gt; that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 3339 format.&lt;/value&gt;\n        /// &lt;remarks&gt;\n        /// &lt;para&gt;\n        /// This method returns a string representation of a &lt;see cref="DateTime"/&gt; that \n        /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n        /// the milliseconds in a date and time value. The &lt;see cref="Rfc3339DateTimeFormat"/&gt; is a valid \n        /// date-time format string for use in the &lt;see cref="DateTime.ToString(String, IFormatProvider)"/&gt; method.\n        /// &lt;/para&gt;\n        /// &lt;/remarks&gt;\n        public static string Rfc3339DateTimeFormat\n        {\n            get\n            {\n                return format;\n            }\n        }\n        #endregion\n\n        #region Rfc3339DateTimePatterns\n        /// &lt;summary&gt;\n        /// Gets an array of the expected formats for RFC 3339 date-time string representations.\n        /// &lt;/summary&gt;\n        /// &lt;value&gt;\n        /// An array of the expected formats for RFC 3339 date-time string representations \n        /// that may used in the &lt;see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/&gt; method.\n        /// &lt;/value&gt;\n        public static string[] Rfc3339DateTimePatterns\n        {\n            get\n            {\n                if (formats.Length &gt; 0)\n                {\n                    return formats;\n                }\n                else\n                {\n                    formats = new string[11];\n\n                    // Rfc3339DateTimePatterns\n                    formats[0] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'fffffffK";\n                    formats[1] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'ffffffK";\n                    formats[2] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'fffffK";\n                    formats[3] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'ffffK";\n                    formats[4] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'fffK";\n                    formats[5] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'ffK";\n                    formats[6] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'fK";\n                    formats[7] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ssK";\n\n                    // Fall back patterns\n                    formats[8] = "yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss\'.\'fffffffK"; // RoundtripDateTimePattern\n                    formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n                    formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n                    return formats;\n                }\n            }\n        }\n        #endregion\n\n        //============================================================\n        //  Public Methods\n        //============================================================\n        #region Parse(string s)\n        /// &lt;summary&gt;\n        /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent.\n        /// &lt;/summary&gt;\n        /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt;\n        /// &lt;returns&gt;A &lt;see cref="DateTime"/&gt; equivalent to the date and time contained in &lt;paramref name="s"/&gt;.&lt;/returns&gt;\n        /// &lt;remarks&gt;\n        /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object.\n        /// &lt;/remarks&gt;\n        /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt;\n        /// &lt;exception cref="FormatException"&gt;&lt;paramref name="s"/&gt; does not contain a valid RFC 3339 string representation of a date and time.&lt;/exception&gt;\n        public static DateTime Parse(string s)\n        {\n            //------------------------------------------------------------\n            //  Validate parameter\n            //------------------------------------------------------------\n            if(s == null)\n            {\n                throw new ArgumentNullException("s");\n            }\n\n            DateTime result;\n            if (Rfc3339DateTime.TryParse(s, out result))\n            {\n                return result;\n            }\n            else\n            {\n                throw new FormatException(String.Format(null, "{0} is not a valid RFC 3339 string representation of a date and time.", s));\n            }\n        }\n        #endregion\n\n        #region ToString(DateTime utcDateTime)\n        /// &lt;summary&gt;\n        /// Converts the value of the specified &lt;see cref="DateTime"/&gt; object to its equivalent string representation.\n        /// &lt;/summary&gt;\n        /// &lt;param name="utcDateTime"&gt;The Coordinated Universal Time (UTC) &lt;see cref="DateTime"/&gt; to convert.&lt;/param&gt;\n        /// &lt;returns&gt;A RFC 3339 string representation of the value of the &lt;paramref name="utcDateTime"/&gt;.&lt;/returns&gt;\n        /// &lt;remarks&gt;\n        /// &lt;para&gt;\n        /// This method returns a string representation of the &lt;paramref name="utcDateTime"/&gt; that \n        /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n        /// the milliseconds in a date and time value.\n        /// &lt;/para&gt;\n        /// &lt;para&gt;\n        /// While it is possible to display higher precision fractions of a second component of a time value, \n        /// that value may not be meaningful. The precision of date and time values depends on the resolution \n        /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock\'s \n        /// resolution is approximately 10-15 milliseconds.\n        /// &lt;/para&gt;\n        /// &lt;/remarks&gt;\n        /// &lt;exception cref="ArgumentException"&gt;The specified &lt;paramref name="utcDateTime"/&gt; object does not represent a &lt;see cref="DateTimeKind.Utc"&gt;Coordinated Universal Time (UTC)&lt;/see&gt; value.&lt;/exception&gt;\n        public static string ToString(DateTime utcDateTime)\n        {\n            if (utcDateTime.Kind != DateTimeKind.Utc)\n            {\n                throw new ArgumentException("utcDateTime");\n            }\n\n            return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n        }\n        #endregion\n\n        #region TryParse(string s, out DateTime result)\n        /// &lt;summary&gt;\n        /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent.\n        /// &lt;/summary&gt;\n        /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt;\n        /// &lt;param name="result"&gt;\n        /// When this method returns, contains the &lt;see cref="DateTime"/&gt; value equivalent to the date and time \n        /// contained in &lt;paramref name="s"/&gt;, if the conversion succeeded, \n        /// or &lt;see cref="DateTime.MinValue"&gt;MinValue&lt;/see&gt; if the conversion failed. \n        /// The conversion fails if the s parameter is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic), \n        /// or does not contain a valid string representation of a date and time. \n        /// This parameter is passed uninitialized.\n        /// &lt;/param&gt;\n        /// &lt;returns&gt;&lt;b&gt;true&lt;/b&gt; if the &lt;paramref name="s"/&gt; parameter was converted successfully; otherwise, &lt;b&gt;false&lt;/b&gt;.&lt;/returns&gt;\n        /// &lt;remarks&gt;\n        /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object.\n        /// &lt;/remarks&gt;\n        public static bool TryParse(string s, out DateTime result)\n        {\n            //------------------------------------------------------------\n            //  Attempt to convert string representation\n            //------------------------------------------------------------\n            bool wasConverted   = false;\n            result              = DateTime.MinValue;\n\n            if (!String.IsNullOrEmpty(s))\n            {\n                DateTime parseResult;\n                if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n                {\n                    result          = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n                    wasConverted    = true;\n                }\n            }\n\n            return wasConverted;\n        }\n        #endregion\n    }\n}\n</code></pre>\n'}, {'answer_id': 17025, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': -1, 'selected': False, 'text': '<p>In .NET (assuming UTC):</p>\n\n<pre><code> datetime.ToString("YYYY-MM-DD\'T\'HH:mm:ssZ")\n</code></pre>\n\n<p><code>DateTime.Parse()</code> can be used to convert back into a <code>DateTime</code> structure.</p>\n'}, {'answer_id': 91146, 'author': 'Matt Howells', 'author_id': 16881, 'author_profile': 'https://Stackoverflow.com/users/16881', 'pm_score': 6, 'selected': False, 'text': '<p>You don\'t need to write your own conversion code. Just use</p>\n\n<pre><code>XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)\n</code></pre>\n\n<p>to parse a RFC-3339 string, and</p>\n\n<pre><code>XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)\n</code></pre>\n\n<p>to convert a (UTC) datetime to a string.</p>\n\n<p><strong>Ref.</strong><br />\n<a href="http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx</a><br />\n<a href="http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx</a></p>\n'}, {'answer_id': 43358041, 'author': 'user1560963', 'author_id': 1560963, 'author_profile': 'https://Stackoverflow.com/users/1560963', 'pm_score': -1, 'selected': False, 'text': '<p>A simple equation will able to obtain the result you are after:</p>\n\n<pre><code>rfcFormat = DateDiff("s", "1/1/1970", Now())\n</code></pre>\n'}, {'answer_id': 59933089, 'author': 'rothschild86', 'author_id': 955459, 'author_profile': 'https://Stackoverflow.com/users/955459', 'pm_score': -1, 'selected': False, 'text': '<p>For completeness sake, Newtonsoft.Json will happily do it as well:</p>\n\n<pre><code>JsonConvert.SerializeObject(DateTime.Now);\n</code></pre>\n\n<p>(Unlike XmlConvert will have have escaped double-quotes on each end.)</p>\n'}, {'answer_id': 69047714, 'author': 'Felipe Maricato Moura', 'author_id': 1837537, 'author_profile': 'https://Stackoverflow.com/users/1837537', 'pm_score': -1, 'selected': False, 'text': '<pre><code>&lt;input asp-for=&quot;StartDate&quot; class=&quot;form-control&quot; value=&quot;@DateTime.Now.ToString(&quot;yyyy-MM-ddThh:mm:ss&quot;)&quot; /&gt;\n</code></pre>\n'}, {'answer_id': 69941381, 'author': 'Andrey Stukalin', 'author_id': 467851, 'author_profile': 'https://Stackoverflow.com/users/467851', 'pm_score': 0, 'selected': False, 'text': '<p><code>System.Text.Json</code> does that as well:</p>\n<pre><code>JsonSerializer.Serialize(DateTime.Now)\n</code></pre>\n'}, {'answer_id': 74110087, 'author': 'Pedro Coelho', 'author_id': 9513617, 'author_profile': 'https://Stackoverflow.com/users/9513617', 'pm_score': 0, 'selected': False, 'text': "<p>This worked for me in <strong>.NET 6</strong>:</p>\n<pre><code>public static class DateTimeExtensions\n{\n     public static string ToRFC3339(this DateTime date)\n     {\n         return date.ToUniversalTime().ToString(&quot;yyyy-MM-dd'T'HH:mm:ss.fffK&quot;);\n     }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/17017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2029/']