當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Elixir NaiveDateTime.add用法及代碼示例


Elixir語言中 NaiveDateTime.add 相關用法介紹如下。

用法:

add(naive_datetime, amount_to_add, unit \\ :second)
(從 1.4.0 開始)
@spec add(Calendar.naive_datetime(), integer(), System.time_unit()) :: t()

將指定的時間量添加到 NaiveDateTime

接受來自 System.time_unit/0 的任何 unit 中的 amount_to_add。負值將及時向後移動。

例子

# adds seconds by default
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2)
~N[2014-10-02 00:29:12]

# accepts negative offsets
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], -2)
~N[2014-10-02 00:29:08]

# can work with other units
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2_000, :millisecond)
~N[2014-10-02 00:29:12]

# keeps the same precision
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10.021], 21, :second)
~N[2014-10-02 00:29:31.021]

# changes below the precision will not be visible
iex> hidden = NaiveDateTime.add(~N[2014-10-02 00:29:10], 21, :millisecond)
iex> hidden.microsecond # ~N[2014-10-02 00:29:10]
{21000, 0}

# from Gregorian seconds
iex> NaiveDateTime.add(~N[0000-01-01 00:00:00], 63_579_428_950)
~N[2014-10-02 00:29:10]

傳遞 DateTime 會自動將其轉換為 NaiveDateTime ,丟棄時區信息:

iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
...>                hour: 23, minute: 0, second: 7, microsecond: {0, 0},
...>                utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
iex> NaiveDateTime.add(dt, 21, :second)
~N[2000-02-29 23:00:28]

相關用法


注:本文由純淨天空篩選整理自elixir-lang.org大神的英文原創作品 NaiveDateTime.add(naive_datetime, amount_to_add, unit \\ :second)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。