RFC 5322 date-time parser using NimbleParsec.
Parses date-time values according to RFC 5322 §3.3, including:
- Standard format: [day-of-week ","] day month year time zone
- Obsolete 2-digit years (RFC 5322 §4.3)
- Named timezones (UT, GMT, EST, EDT, CST, CDT, MST, MDT, PST, PDT)
- Military single-letter zones
Summary
Types
@type t() :: %Mailex.DateTimeParser{ day: 1..31, day_of_week: :mon | :tue | :wed | :thu | :fri | :sat | :sun | nil, hour: 0..23, minute: 0..59, month: 1..12, second: 0..60, year: non_neg_integer(), zone_offset: integer() }
Functions
@spec do_parse(binary(), keyword()) :: {:ok, [term()], rest, context, line, byte_offset} | {:error, reason, rest, context, line, byte_offset} when line: {pos_integer(), byte_offset}, byte_offset: non_neg_integer(), rest: binary(), reason: String.t(), context: map()
Parses the given binary as do_parse.
Returns {:ok, [token], rest, context, position, byte_offset} or
{:error, reason, rest, context, line, byte_offset} where position
describes the location of the do_parse (start position) as {line, offset_to_start_of_line}.
To column where the error occurred can be inferred from byte_offset - offset_to_start_of_line.
Options
:byte_offset- the byte offset for the whole binary, defaults to 0:line- the line and the byte offset into that line, defaults to{1, byte_offset}:context- the initial context value. It will be converted to a map
Parses an RFC 5322 date-time string.
Returns {:ok, struct} with a Mailex.DateTimeParser struct containing
the parsed date-time components.
Examples
iex> Mailex.DateTimeParser.parse("Mon, 15 Jan 2024 09:30:00 -0500")
{:ok, %Mailex.DateTimeParser{
day_of_week: :mon,
day: 15,
month: 1,
year: 2024,
hour: 9,
minute: 30,
second: 0,
zone_offset: -300
}}
iex> Mailex.DateTimeParser.parse("15 Jan 2024 14:30:00 GMT")
{:ok, %Mailex.DateTimeParser{day_of_week: nil, day: 15, month: 1, year: 2024, ...}}
@spec to_datetime(t()) :: {:ok, DateTime.t()} | {:error, term()}
Converts a parsed date-time struct to an Elixir DateTime.
The resulting DateTime preserves the original timezone offset.
Examples
iex> {:ok, dt} = Mailex.DateTimeParser.parse("Mon, 15 Jan 2024 09:30:00 -0500")
iex> {:ok, datetime} = Mailex.DateTimeParser.to_datetime(dt)
iex> datetime.hour
9
iex> datetime.utc_offset
-18000
@spec to_utc_datetime(t()) :: {:ok, DateTime.t()} | {:error, term()}
Converts a parsed date-time struct to a UTC DateTime.
The timezone offset is applied, and the result is in UTC (offset 0).
Examples
iex> {:ok, dt} = Mailex.DateTimeParser.parse("Mon, 15 Jan 2024 09:30:00 -0500")
iex> {:ok, utc_datetime} = Mailex.DateTimeParser.to_utc_datetime(dt)
iex> utc_datetime.hour
14
iex> utc_datetime.utc_offset
0