Skip to content

Commit 32b9b5e

Browse files
committed
adds: DateTime.to_unix can accept non-UTC DateTime structs
1 parent f56ed24 commit 32b9b5e

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

lib/elixir/lib/calendar.ex

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,7 +1056,7 @@ defmodule DateTime do
10561056
@doc """
10571057
Converts the given DateTime to Unix time.
10581058
1059-
The DateTime is expected to be UTC using the ISO calendar
1059+
The DateTime is expected to be using the ISO calendar
10601060
with a year greater than or equal to 1970.
10611061
10621062
It will return the integer with the given unit,
@@ -1067,12 +1067,19 @@ defmodule DateTime do
10671067
iex> 1464096368 |> DateTime.from_unix!() |> DateTime.to_unix()
10681068
1464096368
10691069
1070+
iex> %DateTime{calendar: Calendar.ISO, day: 20, hour: 18, microsecond: {273806, 6}, minute: 58,
1071+
...> month: 11, second: 19, time_zone: "America/Montevideo",
1072+
...> utc_offset: -10800, std_offset: 3600, year: 2014, zone_abbr: "UYST"}
1073+
...> |> DateTime.to_unix()
1074+
1416517099
10701075
"""
10711076
@spec to_unix(DateTime.t, System.time_unit) :: non_neg_integer
1072-
def to_unix(%DateTime{std_offset: 0, utc_offset: 0, time_zone: "Etc/UTC",
1077+
def to_unix(%DateTime{std_offset: std_offset, utc_offset: utc_offset,
10731078
hour: hour, minute: minute, second: second, microsecond: {microsecond, _},
10741079
year: year, month: month, day: day}, unit \\ :seconds) when year >= 1970 do
10751080
seconds = :calendar.datetime_to_gregorian_seconds({{year, month, day}, {hour, minute, second}})
1081+
|> Kernel.-(utc_offset)
1082+
|> Kernel.-(std_offset)
10761083
System.convert_time_unit((seconds - @unix_epoch) * 1_000_000 + microsecond, :microseconds, unit)
10771084
end
10781085

0 commit comments

Comments
 (0)