当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。