Skip to main content

Format C# DateTime as RFC1123 String.

//
// Format DateTime as RFC1123
//
// Ref: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings?redirectedfrom=MSDN#the-rfc1123-r-r-format-specifier
// Source: https://referencesource.microsoft.com/#System.Web/httpserverutility.cs,1513
//
// ex: Fri, 06 Nov 2020 08:17:09 GMT
internal static String FormatHttpDateTime(DateTime dt)
{
    if (dt < DateTime.MaxValue.AddDays(-1) && dt > DateTime.MinValue.AddDays(1))
    {
        dt = dt.ToUniversalTime();
    }

    return dt.ToString("R", DateTimeFormatInfo.InvariantInfo);
}

//
// Format DateTime as RFC1123
//
// Ref: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings?redirectedfrom=MSDN#the-rfc1123-r-r-format-specifier
// Source: https://referencesource.microsoft.com/#System.Web/httpserverutility.cs,1513
//
// ex: Fri, 06 Nov 2020 08:17:09 GMT
internal static String FormatHttpDateTimeUtc(DateTime dt)
{
    return dt.ToString("R", DateTimeFormatInfo.InvariantInfo);
}

//
// Format DateTime as RFC1123
//
// Ref: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.datetimeformatinfo?view=netcore-3.1#examples
// Ref: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings?redirectedfrom=MSDN#the-rfc1123-r-r-format-specifier
// Source: https://referencesource.microsoft.com/#System.Web/httpserverutility.cs,1513
//
// ex: Fri, 06 Nov 2020 08:12:50 GMT
internal static String FormatHttpCookieDateTime(DateTime dt)
{
    if (dt < DateTime.MaxValue.AddDays(-1) && dt > DateTime.MinValue.AddDays(1))
    {
        dt = dt.ToUniversalTime();
    }

    return dt.ToString("ddd, ddd MMM yyyy HH':'mm':'ss 'GMT'", DateTimeFormatInfo.InvariantInfo);
}