C# DateTime - RFC 3339 format
Asked Answered
I

2

9

I am trying to generate RFC 3339 compliant date strings (ie. '2008-03-19T00:00:00.0000000-04:00') however I seem to be having an issue with the offset being invalid. I am using the following:

private string GetDate(DateTime DateTime)
{
    DateTime UtcDateTime = TimeZoneInfo.ConvertTimeToUtc(DateTime);
    return XmlConvert.ToString(UtcDateTime, XmlDateTimeSerializationMode.Utc);
}

but this returns me with a value such as "1977-02-03T05:00:00Z"

I have also attempted using a specific format such as

 utcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK", DateTimeFormatInfo.InvariantInfo); 

But with the same results.


See this existing reference: How do I parse and convert DateTime's to the RFC 3339 date-time format?

Instrumentality answered 16/2, 2011 at 14:42 Comment(3)
Your UtcDateTime is UTC, then why do you expect a time-zone different from 0?Excursive
@CodeInChaos - My understanding was the -04:00 of 2008-03-19T00:00:00.0000000-04:00 represented the Utc OffsetInstrumentality
Yes, since your DataTime uses the UTC-timezone your UTC offset should be 0. And for that the RFC specifies short notation Z. At least that's what I remember. Has been some time since I read that RFC.Excursive
E
11

You are converting your data to UTC, so its timezone offset to UTC is 0:00. The RFC defines a convenient notation for UTC dates, the suffix Z. So this looks like a valid data-string to me.

Excursive answered 16/2, 2011 at 17:30 Comment(0)
M
1

I used this approach for .NET 6:

public static class DateTimeExtensions
{
     public static string ToRFC3339(this DateTime date)
     {
         return date.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
     }
}
Mercurous answered 18/10, 2022 at 11:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.