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?

Community
  • 1
  • 1
cweston
  • 11,297
  • 19
  • 82
  • 107
  • 1
    Your `UtcDateTime` is UTC, then why do you expect a time-zone different from 0? – CodesInChaos Feb 16 '11 at 14:45
  • @CodeInChaos - My understanding was the -04:00 of 2008-03-19T00:00:00.0000000-04:00 represented the Utc Offset – cweston Feb 16 '11 at 14:54
  • 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. – CodesInChaos Feb 16 '11 at 14:56

2 Answers2

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
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");
     }
}
Pedro Coelho
  • 1,411
  • 3
  • 18
  • 31