using System;
using System.Globalization;
namespace EmbedIO.Utilities
{
///
/// Provides standard methods to parse and format s according to various RFCs.
///
public static class HttpDate
{
// https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Net/HttpDateParser.cs
private static readonly string[] DateFormats = {
// "r", // RFC 1123, required output format but too strict for input
"ddd, d MMM yyyy H:m:s 'GMT'", // RFC 1123 (r, except it allows both 1 and 01 for date and time)
"ddd, d MMM yyyy H:m:s 'UTC'", // RFC 1123, UTC
"ddd, d MMM yyyy H:m:s", // RFC 1123, no zone - assume GMT
"d MMM yyyy H:m:s 'GMT'", // RFC 1123, no day-of-week
"d MMM yyyy H:m:s 'UTC'", // RFC 1123, UTC, no day-of-week
"d MMM yyyy H:m:s", // RFC 1123, no day-of-week, no zone
"ddd, d MMM yy H:m:s 'GMT'", // RFC 1123, short year
"ddd, d MMM yy H:m:s 'UTC'", // RFC 1123, UTC, short year
"ddd, d MMM yy H:m:s", // RFC 1123, short year, no zone
"d MMM yy H:m:s 'GMT'", // RFC 1123, no day-of-week, short year
"d MMM yy H:m:s 'UTC'", // RFC 1123, UTC, no day-of-week, short year
"d MMM yy H:m:s", // RFC 1123, no day-of-week, short year, no zone
"dddd, d'-'MMM'-'yy H:m:s 'GMT'", // RFC 850
"dddd, d'-'MMM'-'yy H:m:s 'UTC'", // RFC 850, UTC
"dddd, d'-'MMM'-'yy H:m:s zzz", // RFC 850, offset
"dddd, d'-'MMM'-'yy H:m:s", // RFC 850 no zone
"ddd MMM d H:m:s yyyy", // ANSI C's asctime() format
"ddd, d MMM yyyy H:m:s zzz", // RFC 5322
"ddd, d MMM yyyy H:m:s", // RFC 5322 no zone
"d MMM yyyy H:m:s zzz", // RFC 5322 no day-of-week
"d MMM yyyy H:m:s", // RFC 5322 no day-of-week, no zone
};
///
/// Attempts to parse a string containing a date and time, and possibly a time zone offset,
/// in one of the formats specified in RFC850,
/// RFC1123,
/// and RFC5322,
/// or ANSI C's asctime() format.
///
/// The string to parse.
/// When this method returns ,
/// a representing the parsed date, time, and time zone offset.
/// This parameter is passed uninitialized.
/// if was successfully parsed;
/// otherwise, .
public static bool TryParse(string str, out DateTimeOffset result) =>
DateTimeOffset.TryParseExact(
str,
DateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal,
out result);
///
/// Formats the specified
/// according to RFC1123.
///
/// The to format.
/// A string containing the formatted .
public static string Format(DateTimeOffset dateTimeOffset)
=> dateTimeOffset.ToUniversalTime().ToString("r", DateTimeFormatInfo.InvariantInfo);
///
/// Formats the specified
/// according to RFC1123.
///
/// The to format.
/// A string containing the formatted .
public static string Format(DateTime dateTime)
=> dateTime.ToUniversalTime().ToString("r", DateTimeFormatInfo.InvariantInfo);
}
}