Skip to content

Commit 0af7a45

Browse files
merqlovemichalmuskala
authored andcommitted
Add eliir naivedatetime dump (#132)
1 parent af1d7f7 commit 0af7a45

1 file changed

Lines changed: 30 additions & 6 deletions

File tree

lib/mongo_ecto.ex

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -491,28 +491,52 @@ defmodule Mongo.Ecto do
491491
defp dump_date(_),
492492
do: :error
493493

494-
defp dump_utc_datetime({{_, _, _} = date, {h, m, s, ms}} = v) do
494+
defp dump_utc_datetime({{_, _, _} = date, {h, m, s, ms}}) do
495495
datetime =
496-
{date, {h, m, s}}
497-
|> NaiveDateTime.from_erl!({ms, 6})
498-
|> DateTime.from_naive!("Etc/UTC")
496+
{date, {h, m, s}}
497+
|> NaiveDateTime.from_erl!({ms, 6})
498+
|> datetime_from_naive!("Etc/UTC")
499499

500500
{:ok, datetime}
501501
end
502502
defp dump_utc_datetime(_),
503503
do: :error
504504

505-
defp dump_naive_datetime({{_, _, _} = date, {h, m, s, ms}} = v) do
505+
defp dump_naive_datetime({{_, _, _} = date, {h, m, s, ms}}) do
506506
datetime =
507507
{date, {h, m, s}}
508508
|> NaiveDateTime.from_erl!({ms, 6})
509-
|> DateTime.from_naive!("Etc/UTC")
509+
|> datetime_from_naive!("Etc/UTC")
510510

511511
{:ok, datetime}
512512
end
513513
defp dump_naive_datetime(_),
514514
do: :error
515515

516+
@doc """
517+
Copy from the Elixir 1.4.5. TODO: Replace with native methods, when we stick on ~> 1.4.
518+
Source: https://github.com/elixir-lang/elixir/blob/v1.4/lib/elixir/lib/calendar.ex#L1477
519+
"""
520+
defp datetime_from_naive(%NaiveDateTime{hour: hour, minute: minute, second: second, microsecond: microsecond,
521+
year: year, month: month, day: day}, "Etc/UTC") do
522+
{:ok, %DateTime{year: year, month: month, day: day,
523+
hour: hour, minute: minute, second: second, microsecond: microsecond,
524+
std_offset: 0, utc_offset: 0, zone_abbr: "UTC", time_zone: "Etc/UTC"}}
525+
end
526+
527+
@doc """
528+
Copy from the Elixir 1.4.5. TODO: Replace with native methods, when we stick on ~> 1.4.
529+
Source: https://github.com/elixir-lang/elixir/blob/v1.4/lib/elixir/lib/calendar.ex#L1477
530+
"""
531+
defp datetime_from_naive!(naive_datetime, time_zone) do
532+
case datetime_from_naive(naive_datetime, time_zone) do
533+
{:ok, datetime} ->
534+
datetime
535+
{:error, reason} ->
536+
raise ArgumentError, "cannot parse #{inspect naive_datetime} to datetime, reason: #{inspect reason}"
537+
end
538+
end
539+
516540
defp dump_binary(binary, subtype) when is_binary(binary),
517541
do: {:ok, %BSON.Binary{binary: binary, subtype: subtype}}
518542
defp dump_binary(_, _),

0 commit comments

Comments
 (0)