timex v3.2.2 Timex View Source

Timex

Master Hex.pm Version InchCI Coverage Status

Timex is a rich, comprehensive Date/Time library for Elixir projects, with full timezone support via the :tzdata package. If you need to manipulate dates, times, datetimes, timestamps, etc., then Timex is for you! It is very easy to use Timex types in place of default Erlang types, as well as Ecto types via the timex_ecto package.

The complete documentation for Timex is located here.

Migrating to Timex 3.x

See the Migrating section further down for details. If you are migrating from earlier than 2.x, please review this migration doc for 1.x to 2.x.

Timex 3.0 is a significant rewrite, in order to accommodate Elixir 1.3’s new Calendar types in a semantically correct way. The external API is mostly the same, but there are changes, many without deprecations, so please read the changelog carefully.

Getting Started

There are some brief examples on usage below, but I highly recommend you review the API docs here, there are many examples, and some extra pages with richer documentation on specific subjects such as custom formatters/parsers, etc.

Adding Timex To Your Project

To use Timex with your projects, edit your mix.exs file and add it as a dependency:

defp deps do
  [{:timex, "~> 3.1"}]
end

defp application do
  [applications: [:timex]]
end

Quickfast introduction

To use Timex, I recommend you add use Timex to the top of the module where you will be working with Timex modules, all it does is alias common types so you can work with them more comfortably. If you want to see the specific aliases added, check the top of the Timex module, in the __using__/1 macro definition.

Here’s a few simple examples:

> use Timex
> Timex.today
~D[2016-02-29]

> datetime = Timex.now
#<DateTime(2016-02-29T12:30:30.120+00:00Z Etc/UTC)

> Timex.now("America/Chicago")
#<DateTime(2016-02-29T06:30:30.120-06:00 America/Chicago)

> Duration.now
#<Duration(P46Y6M24DT21H57M33.977711S)>

> {:ok, default_str} = Timex.format(datetime, "{ISO:Extended}")
{:ok, "2016-02-29T12:30:30.120+00:00"}

> {:ok, relative_str} = Timex.shift(datetime, minutes: -3) |> Timex.format("{relative}", :relative)
{:ok, "3 minutes ago"}

> strftime_str = Timex.format!(datetime, "%FT%T%:z", :strftime)
"2016-02-29T12:30:30+00:00"

> Timex.parse(strftime_str, "{ISO:Extended}")
{:ok, #<DateTime(2016-02-29T12:30:30.120+00:00 Etc/Utc)}

> Timex.parse!(strftime_str, "%FT%T%:z", :strftime)
#<DateTime(2016-02-29T12:30:30.120+00:00 Etc/Utc)

> Duration.diff(Duration.now, Duration.zero, :days)
16850

> Timex.shift(date, days: 3)
~D[2016-03-03]

> Timex.shift(datetime, hours: 2, minutes: 13)
#<DateTime(2016-02-29T14:43:30.120Z Etc/UTC)>

> timezone = Timezone.get("America/Chicago", Timex.now)
#<TimezoneInfo(America/Chicago - CDT (-06:00:00))>

> Timezone.convert(datetime, timezone)
#<DateTime(2016-02-29T06:30:30.120-06:00 America/Chicago)>

> Timex.before?(Timex.today, Timex.shift(Timex.today, days: 1))
true

> Timex.before?(Timex.shift(Timex.today, days: 1), Timex.today)
false

> interval = Timex.Interval.new(from: ~D[2016-03-03], until: [days: 3])
%Timex.Interval{from: ~N[2016-03-03 00:00:00], left_open: false,
 right_open: true, step: [days: 1], until: ~N[2016-03-06 00:00:00]}

> ~D[2016-03-04] in interval
true

> ~N[2016-03-04 00:00:00] in interval
true

> ~N[2016-03-02 00:00:00] in interval
false

> Timex.Interval.overlaps?(Timex.Interval.new(from: ~D[2016-03-04], until: [days: 1]), interval)
true

> Timex.Interval.overlaps?(Timex.Interval.new(from: ~D[2016-03-07], until: [days: 1]), interval)
false

There are a ton of other functions, all of which work with Erlang datetime tuples, Date, NaiveDateTime, and DateTime. The Duration module contains functions for working with Durations, including Erlang timestamps (such as those returned from :timer.tc)

Extensibility

Timex exposes a number of extension points for you, in order to accommodate different use cases:

Timex itself defines it’s core operations on the Date, DateTime, and NaiveDateTime types using the Timex.Protocol protocol. From there, all other Timex functionality is derived. If you have custom date/datetime types you want to use with Timex, this is the protocol you would need to implement.

Timex also defines a Timex.Comparable protocol, which you can extend to add comparisons to custom date/datetime types.

You can provide your own formatter/parser for datetime strings by implementing the Timex.Format.DateTime.Formatter and/or Timex.Parse.DateTime.Parser behaviours, depending on your needs.

Common Issues

iso_* Functions

Timex functions of the form iso_* behave based on how the ISO calendar represents dates/times and not the ISO8601 date format. This confusion has occurred before, and it’s important to note this!

Timex with escript

If you need to use Timex from within an escript, add {:tzdata, "~> 0.1.8", override: true} to your deps, more recent versions of :tzdata are unable to work in an escript because of the need to load ETS table files from priv, and due to the way ETS loads these files, it’s not possible to do so.

Automatic time zone updates

Timex includes the Tzdata library for time zone data. Tzdata has an automatic update capability that fetches updates from IANA and which is enabled by default; if you want to disable it, check the Tzdata documentation for details.

Migrating

If you have been using Timex pre-3.x, and you are looking to migrate, it will be fairly painless as long as you review the CHANGELOG.md file and make note of anything that has changed which you are using. In almost every single case, the functionality has simply moved, or is accessed slightly differently. In some cases behaviour has changed, but the old behaviour can be achieved manually. For those things which were removed or are no longer available, it is almost certainly because those things are no longer recommended, or no longer make sense for this library. If I have missed something, or there is a good justification for re-adding something which was removed, I’m always open to discussing it on the issue tracker.

Overview of 3.x changes

Please see the CHANGELOG.md file for the list of all changes made, below are a brief recap of the major points, and instructions on how to migrate your existing Timex-based code to 3.x.

  • Virtually all of Timex’s API is consolidated around three modules: Timex, Duration, and Interval. There are public APIs in other modules of course, but most everything you do can be done via one of those three.
  • All Timex-provided types have been removed, with the exception of Time which has been renamed to Duration to better fit it’s purpose, TimezoneInfo, which is still used internally, and accessible externally, and AmbiguousDateTime, which is still required when dealing with ambiguous DateTime structs. Date and DateTime are now part of Elixir 1.3, and NaiveDateTime has been added as a first class type as well.
  • Conversions have been rehashed, and are now accessed via the Timex module: to_date, to_datetime, to_naive_datetime, to_erl, to_unix, to_gregorian_seconds, and to_gregorian_microseconds. Use these to convert back and forth between types. With very few exceptions, there are no from_* conversions. You must construct a standard type either with the standard library functions (such as NaiveDateTime.new), or by converting from another standard type (i.e. Erlang datetime tuple to NaiveDateTime).

A variety of improvements came about as well:

  • Microsecond precision everywhere it can be maintained
  • Various bug fixes from the 2.x release which were held back
  • A lot of code clean up
  • Faster compilation
  • Fixed typespecs, docs, and tests across the board
  • Added Julian calendar support

Roadmap

The following are an unordered list of things I plan for Timex in the future, if you have specific requests, please open an issue with “RFC” in the title, and we can discuss it, and hopefully get input from the community.

  • 100% test coverage (well under way!)
  • QuickCheck tests (haven’t started this, but I really want to start ASAP)
  • {ASP.NET} formatting/parsing token for interop with .NET services (probably in the next release)
  • Relative time formatter/parser, along the lines of Moment.js’s fromNow, toNow, timeTo, and timeFrom formatting functions.
  • Calendar time formatter/parser, along the lines of Moment.js’s calendar time formatter
  • Recurring dates/times API

License

This software is licensed under the MIT license.

Link to this section Summary

Functions

Add time to a date using a Duration Same as shift(date, Duration.from_minutes(5), :duration)

Returns a boolean indicating whether the first Timex.Comparable occurs after the second

Returns a boolean indicating whether the first Timex.Comparable occurs before the second

Returns a DateTime representing the beginning of the day

Given a date returns a date at the beginning of the month

Same as beginning_of_month/1, except takes year and month as distinct arguments

Given a date returns a date at the beginning of the quarter

Shifts the date to the beginning of the week

Given a date or a number create a date at the beginning of that year

Returns a boolean indicating whether the first Timex.Comparable occurs between the second and third

Gets the current century

Given a date, get the century this date is in

See docs for compare/3

Compare two Timex.Comparable values, returning one of the following values

Returns the ordinal day number of the date

Get the name of the day corresponding to the provided number

Get the short name of the day corresponding to the provided number

Get the day of the week corresponding to the given name

Return the number of days in the month which the date falls on

Same as days_in_month/2, except takes year and month as distinct arguments

Number of days to the beginning of the week

Number of days to the end of the week

See docs for diff/3

Calculate time interval between two dates. The result will be a signed integer, negative if the first date/time comes before the second, and positive if the first date/time comes after the second

Returns a DateTime representing the end of the day

Given a date returns a date at the end of the month

Same as end_of_month/1, except takes year and month as distinct arguments

Given a date or a year and month returns a date at the end of the quarter

Same as end_of_quarter/1, except takes year and month as distinct arguments

Returns a Date or a DateTime representing the end of the week, depending on the input, i.e. if you pass a date/time value which represents just a date, you will get back a Date, if both a date and time are present, you will get back a DateTime

Given a date or a number create a date at the end of that year

Returns a Date representing the start of the UNIX epoch

Returns a boolean indicating whether the two Timex.Comparable values are equivalent

Formats a date/time value using the given format string (and optional formatter)

Same as format/2, except using a custom formatter

Same as format/2, except format! raises on error

Same as format/3, except format! raises on error

Formats an Erlang timestamp using the ISO-8601 duration format, or optionally, with a custom formatter of your choosing

Same as format_duration/1, except it also accepts a formatter

Convert an iso ordinal day number to the day it represents in the current year

Same as from_iso_day/1, except you can expect the following based on the second parameter

Given an ISO triplet {year, week number, weekday}, convert it to a Date struct

Formats a DateTime using a fuzzy relative duration, from now

Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now

Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now, translated using the given locale

Return a boolean indicating whether the given year is a leap year. You may pase a date or a year number

Return a boolean indicating whether the given date is valid

Returns a boolean indicating whether the provided term represents a valid time, valid times are one of

Returns a boolean indicating whether the provided term represents a valid timezone, valid timezones are one of

Return a 3-tuple {year, week number, weekday} for the given Date/DateTime

Return a pair {year, week number} (as defined by ISO 8601) that the given Date/DateTime value falls on

Same as iso_week/1, except this takes a year, month, and day as distinct arguments

Same as format/2, except takes a locale name to translate text to

Same as lformat/3, except takes a formatter as it’s last argument

Same as lformat/3, except local_format! raises on error

Same as lformat/4, except local_format! raises on error

Same as format_duration/1, except takes a locale for use in translation

Same as lformat_duration/2, except takes a formatter as an argument

Returns a DateTime representing the current moment in time in the local timezone

Returns a DateTime representing the given date/time in the local timezone

Get the name of the month corresponding to the provided number

Get the short name of the month corresponding to the provided number

Get the number of the month corresponding to the given name

Given a unit to normalize, and the value to normalize, produces a valid value for that unit, clamped to whatever boundaries are defined for that unit

Returns a DateTime representing the current moment in time in UTC

Returns a DateTime representing the current moment in time in the provided timezone

Parses a datetime string into a DateTime struct, using the provided format string (and optional tokenizer)

Same as parse/2 and parse/3, except parse! raises on error

Returns what quarter of the year the given date/time falls in

Return a new date/time value with the specified fields replaced by new values

A single function for adjusting the date using various units: duration, microseconds, seconds, minutes, hours, days, weeks, months, years

Called when an application is started

Subtract time from a date using a Duration Same as shift(date, Duration.from_minutes(5) |> Duration.invert, :timestamp)

Get a TimezoneInfo object for the specified offset or name

Returns a list of all valid timezone names in the Olson database

Convert a date/time value to a Date struct

Convert a date/time value and timezone name to a DateTime struct. If the DateTime is ambiguous and cannot be resolved, an AmbiguousDateTime will be returned, allowing the developer to choose which of the two choices is desired

Convert a date/time value to it’s Erlang representation

Convert a date/time value to gregorian microseconds (microseconds since start of year zero)

Convert a date/time value to gregorian seconds (seconds since start of year zero)

Convert a date/time value to a Julian calendar date number

Convert a date/time value to a NaiveDateTime struct

Convert a date/time value to seconds since the UNIX epoch

Returns a Date representing the current day in UTC

Given a format string, validates that the format string is valid for the Default formatter

Returns the week number of the date provided, starting at 1

Same as week_of_month/1, except takes year, month, and day as distinct arguments

Return weekday number (as defined by ISO 8601) of the specified date

Returns a Date representing the start of the Gregorian epoch

Link to this section Types

Link to this type between_options() View Source
between_options() :: [{:inclusive, boolean()}]
Link to this type set_options() View Source
set_options() :: [
  validate: boolean(),
  datetime: Timex.Types.datetime(),
  date: Timex.Types.date(),
  year: Timex.Types.year(),
  month: Timex.Types.month(),
  day: Timex.Types.day(),
  hour: Timex.Types.hour(),
  minute: Timex.Types.minute(),
  second: Timex.Types.second(),
  microsecond: Timex.Types.microsecond()
]
Link to this type shift_options() View Source
shift_options() :: [
  microseconds: integer(),
  milliseconds: integer(),
  seconds: integer(),
  minutes: integer(),
  hours: integer(),
  days: integer(),
  weeks: integer(),
  months: integer(),
  years: integer(),
  duration: Timex.Duration.t()
]

Link to this section Functions

Add time to a date using a Duration Same as shift(date, Duration.from_minutes(5), :duration).

Link to this function after?(a, b) View Source
after?(Time, Time) :: boolean() | {:error, term()}
after?(Timex.Comparable.comparable(), Timex.Comparable.comparable()) ::
  boolean() | {:error, term()}

Returns a boolean indicating whether the first Timex.Comparable occurs after the second

Link to this function before?(a, b) View Source
before?(Time, Time) :: boolean() | {:error, term()}
before?(Timex.Comparable.comparable(), Timex.Comparable.comparable()) ::
  boolean() | {:error, term()}

Returns a boolean indicating whether the first Timex.Comparable occurs before the second

Link to this function beginning_of_day(datetime) View Source
beginning_of_day(Timex.Types.valid_datetime()) ::
  Timex.Types.valid_datetime() | {:error, term()}

Returns a DateTime representing the beginning of the day

Examples

iex> date = Timex.to_datetime({{2015, 1, 1}, {13, 14, 15}}, "Etc/UTC")
iex> Timex.beginning_of_day(date)
Timex.to_datetime({{2015, 1, 1}, {0, 0, 0}}, "Etc/UTC")

iex> date = ~D[2015-01-01]
...> Timex.beginning_of_day(date)
~D[2015-01-01]
Link to this function beginning_of_month(datetime) View Source
beginning_of_month(Timex.Types.valid_datetime()) ::
  Timex.Types.valid_datetime() | {:error, term()}

Given a date returns a date at the beginning of the month.

iex> date = Timex.to_datetime({{2015, 6, 15}, {12,30,0}}, "Europe/Paris")
iex> Timex.beginning_of_month(date)
Timex.to_datetime({{2015, 6, 1}, {0, 0, 0}}, "Europe/Paris")
Link to this function beginning_of_month(year, month) View Source
beginning_of_month(Timex.Types.year(), Timex.Types.month()) ::
  Date.t() | {:error, term()}

Same as beginning_of_month/1, except takes year and month as distinct arguments

Link to this function beginning_of_quarter(datetime) View Source
beginning_of_quarter(Timex.Types.valid_datetime()) ::
  Timex.Types.valid_datetime() | {:error, term()}

Given a date returns a date at the beginning of the quarter.

iex> date = Timex.to_datetime({{2015, 6, 15}, {12,30,0}}, "America/Chicago")
iex> Timex.beginning_of_quarter(date)
Timex.to_datetime({{2015, 4, 1}, {0, 0, 0}}, "America/Chicago")
Link to this function beginning_of_week(date, weekstart \\ :mon) View Source

Shifts the date to the beginning of the week

The weekstart can between 1..7, an atom e.g. :mon, or a string e.g. “Monday”

Examples

iex> date = ~N[2015-11-30T13:30:30] # Monday 30th November
iex> Timex.beginning_of_week(date)
~N[2015-11-30T00:00:00]

iex> date = ~D[2015-11-30] # Monday 30th November
iex> Timex.beginning_of_week(date, :sun)
~D[2015-11-29]

Given a date or a number create a date at the beginning of that year

Examples

iex> date = ~N[2015-06-15T00:00:00]
iex> Timex.beginning_of_year(date)
~N[2015-01-01T00:00:00]

iex> Timex.beginning_of_year(2015)
~D[2015-01-01]
Link to this function between?(a, start, ending, options \\ []) View Source
between?(Time, Time, Time, between_options()) :: boolean() | {:error, term()}
between?(
  Timex.Comparable.comparable(),
  Timex.Comparable.comparable(),
  Timex.Comparable.comparable(),
  between_options()
) :: boolean() | {:error, term()}

Returns a boolean indicating whether the first Timex.Comparable occurs between the second and third.

By default, the startand ending bounds are exclusive. You can opt for inclusive bounds by setting the :inclusive option to true.

Link to this function century() View Source
century() :: non_neg_integer() | {:error, term()}

Gets the current century

Examples

iex> Elixir.Timex.century
21

Given a date, get the century this date is in.

Examples

iex> Timex.today |> Elixir.Timex.century
21
iex> Timex.now |> Elixir.Timex.century
21
iex> Elixir.Timex.century(2016)
21

Compare two Timex.Comparable values, returning one of the following values:

  • -1 — the first date comes before the second one
  • 0 — both arguments represent the same date when coalesced to the same timezone.
  • 1 — the first date comes after the second one

You can provide a few reference constants for the second argument:

  • :epoch will compare the first parameter against the Date/DateTime of the first moment of the UNIX epoch
  • :zero will compare the first parameter against the Date/DateTime of the first moment of year zero
  • :distant_past will compare the first parameter against a date/time infinitely in the past (i.e. it will always return 1)
  • :distant_future will compare the first parameter against a date/time infinitely in the future (i.e. it will always return -1)

You can optionally specify a comparison granularity, any of the following:

  • :years
  • :months
  • :weeks
  • :calendar_weeks (weeks of the calendar as opposed to actual weeks in terms of days)
  • :days
  • :hours
  • :minutes
  • :seconds
  • :milliseconds
  • :microseconds (default)
  • :duration

and the dates will be compared with the cooresponding accuracy. The default granularity is :microseconds.

Examples

iex> date1 = ~D[2014-03-04]
iex> date2 = ~D[2015-03-04]
iex> Timex.compare(date1, date2, :years)
-1
iex> Timex.compare(date2, date1, :years)
1
iex> Timex.compare(date1, date1)
0

Returns the ordinal day number of the date.

Examples

iex> Timex.day(~D[2015-06-26])
177
Link to this function day_name(num) View Source
day_name(Timex.Types.weekday()) ::
  String.t() | {:error, :invalid_weekday_number}

Get the name of the day corresponding to the provided number

Examples

iex> Elixir.Timex.day_name(1)
"Monday"
iex> Elixir.Timex.day_name(0)
{:error, :invalid_weekday_number}
Link to this function day_shortname(num) View Source
day_shortname(Timex.Types.weekday()) ::
  String.t() | {:error, :invalid_weekday_number}

Get the short name of the day corresponding to the provided number

Examples

iex> Elixir.Timex.day_shortname(1)
"Mon"
iex> Elixir.Timex.day_shortname(0)
{:error, :invalid_weekday_number}
Link to this function day_to_num(arg1) View Source
day_to_num(binary() | atom()) ::
  Timex.Types.weekday() | {:error, :invalid_day_name}

Get the day of the week corresponding to the given name.

The name can be given as a string of the weekday name or its first three characters (lowercase or capitalized) or as a corresponding atom (lowercase only).

Examples

iex> Elixir.Timex.day_to_num("Monday")
1
iex> Elixir.Timex.day_to_num("monday")
1
iex> Elixir.Timex.day_to_num("Mon")
1
iex> Elixir.Timex.day_to_num("mon")
1
iex> Elixir.Timex.day_to_num(:mon)
1
iex> Elixir.Timex.day_to_num(:sunday)
7
Link to this function days_in_month(datetime) View Source
days_in_month(Timex.Types.valid_datetime()) ::
  Timex.Types.num_of_days() | {:error, term()}

Return the number of days in the month which the date falls on.

Examples

iex> Timex.days_in_month(~D[1970-01-01])
31
Link to this function days_in_month(year, month) View Source
days_in_month(Timex.Types.year(), Timex.Types.month()) ::
  Timex.Types.num_of_days() | {:error, term()}

Same as days_in_month/2, except takes year and month as distinct arguments

Link to this function days_to_beginning_of_week(date, weekstart \\ 1) View Source
days_to_beginning_of_week(Timex.Types.valid_datetime(), Timex.Types.weekstart()) ::
  integer() | {:error, term()}

Number of days to the beginning of the week

The weekstart determines which is the first day of the week, defaults to monday. It can be a number between 1..7 (1 is monday, 7 is sunday), or any value accepted by day_to_num/1.

Examples

iex> date = ~D[2015-11-30] # Monday 30th November
iex> Timex.days_to_beginning_of_week(date)
0

iex> date = ~D[2015-11-30] # Monday 30th November
iex> Timex.days_to_beginning_of_week(date, :sun)
1
Link to this function days_to_end_of_week(date, weekstart \\ :mon) View Source
days_to_end_of_week(Timex.Types.valid_datetime(), Timex.Types.weekstart()) ::
  integer() | {:error, term()}

Number of days to the end of the week.

The weekstart can between 1..7, an atom e.g. :mon, or a string e.g. “Monday”

Examples

Week starting Monday
iex> date = ~D[2015-11-30] # Monday 30th November
iex> Timex.days_to_end_of_week(date)
6

Week starting Sunday
iex> date = ~D[2015-11-30] # Monday 30th November
iex> Timex.days_to_end_of_week(date, :sun)
5

Calculate time interval between two dates. The result will be a signed integer, negative if the first date/time comes before the second, and positive if the first date/time comes after the second.

You must specify one of the following units:

  • :years
  • :months
  • :calendar_weeks (weeks of the calendar as opposed to actual weeks in terms of days)
  • :weeks
  • :days
  • :hours
  • :minutes
  • :seconds
  • :duration

and the result will be an integer value of those units or a Duration.

Returns a DateTime representing the end of the day

Examples

iex> date = ~N[2015-01-01T13:14:15]
...> Timex.end_of_day(date)
~N[2015-01-01T23:59:59.999999]

Given a date returns a date at the end of the month.

iex> date = ~N[2015-06-15T12:30:00Z]
iex> Timex.end_of_month(date)
~N[2015-06-30T23:59:59.999999Z]
Link to this function end_of_month(year, month) View Source
end_of_month(Timex.Types.year(), Timex.Types.month()) :: Date.t()

Same as end_of_month/1, except takes year and month as distinct arguments

Examples

iex> Timex.end_of_month(2016, 2)
~D[2016-02-29]
Link to this function end_of_quarter(datetime) View Source
end_of_quarter(Timex.Types.valid_datetime()) ::
  Timex.Types.valid_datetime() | {:error, term()}

Given a date or a year and month returns a date at the end of the quarter.

iex> date = ~N[2015-06-15T12:30:00]
...> Timex.end_of_quarter(date)
~N[2015-06-30T23:59:59.999999]

iex> Timex.end_of_quarter(2015, 4)
~D[2015-06-30]
Link to this function end_of_quarter(year, month) View Source
end_of_quarter(Timex.Types.year(), Timex.Types.month()) ::
  Date.t() | {:error, term()}

Same as end_of_quarter/1, except takes year and month as distinct arguments

Link to this function end_of_week(datetime, weekstart \\ 1) View Source

Returns a Date or a DateTime representing the end of the week, depending on the input, i.e. if you pass a date/time value which represents just a date, you will get back a Date, if both a date and time are present, you will get back a DateTime

The weekstart can between 1..7, an atom e.g. :mon, or a string e.g. “Monday”

Examples

iex> date = ~N[2015-11-30T13:30:30] # Monday 30th November
...> Timex.end_of_week(date)
~N[2015-12-06T23:59:59.999999]

iex> date = ~D[2015-11-30] # Monday 30th November
...> Timex.end_of_week(date, :sun)
~D[2015-12-05]

Given a date or a number create a date at the end of that year

Examples

iex> date = ~N[2015-06-15T00:00:00]
iex> Timex.end_of_year(date)
~N[2015-12-31T23:59:59.999999]

iex> Timex.end_of_year(2015)
~D[2015-12-31]

Returns a Date representing the start of the UNIX epoch

Link to this function equal?(a, a, granularity \\ :seconds) View Source
equal?(Time, Time, Timex.Comparable.granularity()) ::
  boolean() | {:error, :badarg}
equal?(
  Timex.Comparable.comparable(),
  Timex.Comparable.comparable(),
  Timex.Comparable.granularity()
) :: boolean() | {:error, :badarg}

Returns a boolean indicating whether the two Timex.Comparable values are equivalent.

Equality here implies that the two Comparables represent the same moment in time (with the given granularity), not equality of the data structure.

The options for granularity is the same as for compare/3, defaults to :seconds.

Examples

iex> date1 = ~D[2014-03-01]
...> date2 = ~D[2014-03-01]
...> Elixir.Timex.equal?(date1, date2)
true

iex> date1 = ~D[2014-03-01]
...> date2 = Timex.to_datetime({2014, 3, 1}, "Etc/UTC")
...> Elixir.Timex.equal?(date1, date2)
true
Link to this function format(datetime, format_string) View Source
format(Timex.Types.valid_datetime(), format :: String.t()) ::
  {:ok, String.t()} | {:error, term()}

Formats a date/time value using the given format string (and optional formatter).

See Timex.Format.DateTime.Formatters.Default or Timex.Format.DateTime.Formatters.Strftime for documentation on the syntax supported by those formatters.

To use the Default formatter, simply call format/2. To use the Strftime formatter, you can either alias and pass Strftime by module name, or as a shortcut, you can pass :strftime instead.

Formatting will convert other dates than Elixir date types (Date, DateTime, NaiveDateTime) to a NaiveDateTime using to_naive_datetime/1 before formatting.

Examples

iex> date = ~D[2016-02-29]
...> Timex.format!(date, "{YYYY}-{0M}-{D}")
"2016-02-29"

iex> datetime = Timex.to_datetime({{2016,2,29},{22,25,0}}, "Etc/UTC")
...> Timex.format!(datetime, "{ISO:Extended}")
"2016-02-29T22:25:00+00:00"
Link to this function format(datetime, format_string, formatter) View Source
format(Timex.Types.valid_datetime(), format :: String.t(), formatter :: atom()) ::
  {:ok, String.t()} | {:error, term()}

Same as format/2, except using a custom formatter

Examples

iex> use Timex
...> datetime = Timex.to_datetime({{2016,2,29},{22,25,0}}, "America/Chicago")
iex> Timex.format!(datetime, "%FT%T%:z", :strftime)
"2016-02-29T22:25:00-06:00"
Link to this function format!(datetime, format_string) View Source
format!(Timex.Types.valid_datetime(), format :: String.t()) ::
  String.t() | no_return()

Same as format/2, except format! raises on error.

See format/2 docs for usage examples.

Link to this function format!(datetime, format_string, formatter) View Source
format!(Timex.Types.valid_datetime(), format :: String.t(), formatter :: atom()) ::
  String.t() | no_return()

Same as format/3, except format! raises on error.

See format/3 docs for usage examples

Link to this function format_duration(timestamp) View Source
format_duration(Timex.Duration.t()) :: String.t() | {:error, term()}

Formats an Erlang timestamp using the ISO-8601 duration format, or optionally, with a custom formatter of your choosing.

See Timex.Format.Duration.Formatters.Default or Timex.Format.Duration.Formatters.Humanized for documentation on the specific formatter behaviour.

To use the Default formatter, simply call format_duration/2. To use the Humanized formatter, you can either alias and pass Humanized by module name, or as a shortcut, you can pass :humanized instead.

Examples

iex> use Timex
...> duration = Duration.from_seconds(Timex.to_unix({2016, 2, 29}))
...> Timex.format_duration(duration)
"P46Y2M10D"

iex> use Timex
...> duration = Duration.from_seconds(Timex.to_unix({2016, 2, 29}))
...> Timex.format_duration(duration, :humanized)
"46 years, 2 months, 1 week, 3 days"

iex> use Timex
...> datetime = Duration.from_seconds(Timex.to_unix(~N[2016-02-29T22:25:00]))
...> Timex.format_duration(datetime, :humanized)
"46 years, 2 months, 1 week, 3 days, 22 hours, 25 minutes"
Link to this function format_duration(timestamp, formatter) View Source
format_duration(Timex.Duration.t(), atom()) :: String.t() | {:error, term()}

Same as format_duration/1, except it also accepts a formatter

Link to this function from_iso_day(day) View Source
from_iso_day(non_neg_integer()) :: Date.t() | {:error, term()}

Convert an iso ordinal day number to the day it represents in the current year.

## Examples

iex> %Date{:year => year} = Timex.from_iso_day(180)
...> %Date{:year => todays_year} = Timex.today()
...> year == todays_year
true

Same as from_iso_day/1, except you can expect the following based on the second parameter:

  • If an integer year is given, the result will be a Date struct
  • For any date/time value, the result will be in the same format (i.e. Date -> Date)

In all cases, the resulting value will be the date representation of the provided ISO day in that year

Examples

Creating a Date from the given day

iex> use Timex
...> expected = ~D[2015-06-29]
...> (expected === Timex.from_iso_day(180, 2015))
true

Creating a Date/DateTime from the given day

iex> use Timex
...> expected = Timex.to_datetime({{2015, 6, 29}, {0,0,0}}, "Etc/UTC")
...> beginning = Timex.to_datetime({{2015,1,1}, {0,0,0}}, "Etc/UTC")
...> (expected === Timex.from_iso_day(180, beginning))
true

Shifting a Date/DateTime to the given day

iex> use Timex
...> date = Timex.to_datetime({{2015,6,26}, {12,0,0}}, "Etc/UTC")
...> expected = Timex.to_datetime({{2015, 6, 29}, {12,0,0}}, "Etc/UTC")
...> (Timex.from_iso_day(180, date) === expected)
true
Link to this function from_iso_triplet(arg) View Source
from_iso_triplet(Timex.Types.iso_triplet()) :: Date.t() | {:error, term()}

Given an ISO triplet {year, week number, weekday}, convert it to a Date struct.

Examples

iex> expected = Timex.to_date({2014, 1, 28})
iex> Timex.from_iso_triplet({2014, 5, 2}) === expected
true
Link to this function from_now(datetime) View Source
from_now(Timex.Types.valid_datetime()) :: String.t() | {:error, term()}

Formats a DateTime using a fuzzy relative duration, from now.

Examples

iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: 2, hours: 1))
"in 2 days"

iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: -2))
"2 days ago"
Link to this function from_now(datetime, locale) View Source
from_now(Timex.Types.valid_datetime(), String.t()) ::
  String.t() | {:error, term()}
from_now(Timex.Types.valid_datetime(), Timex.Types.valid_datetime()) ::
  String.t() | {:error, term()}

Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now

Link to this function from_now(datetime, reference_date, locale) View Source

Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now, translated using the given locale

Link to this function from_unix(secs, unit \\ :seconds) View Source
from_unix(secs :: non_neg_integer(), :native | System.time_unit()) ::
  DateTime.t() | no_return()

Delegates to DateTime.from_unix!/2. To recap the docs:

Converts the given Unix time to DateTime.

The integer can be given in different units according to System.convert_time_unit/3 and it will be converted to microseconds internally. Defaults to :seconds.

Unix times are always in UTC and therefore the DateTime will be returned in UTC.

Return a boolean indicating whether the given year is a leap year. You may pase a date or a year number.

Examples

iex> Timex.epoch() |> Elixir.Timex.is_leap?
false
iex> Elixir.Timex.is_leap?(2012)
true
Link to this function is_valid?(datetime) View Source
is_valid?(Timex.Types.valid_datetime()) :: boolean() | {:error, term()}

Return a boolean indicating whether the given date is valid.

Examples

iex> use Timex
...> Timex.is_valid?(~N[0001-01-01T01:01:01])
true

iex> use Timex
...> %Date{year: 1, day: 1, month: 13} |> Elixir.Timex.is_valid?
false
Link to this function is_valid_time?(arg1) View Source
is_valid_time?(term()) :: boolean()

Returns a boolean indicating whether the provided term represents a valid time, valid times are one of:

  • {hour, min, sec}
  • {hour, min, sec, ms}
Link to this function is_valid_timezone?(timezone) View Source
is_valid_timezone?(term()) :: boolean()

Returns a boolean indicating whether the provided term represents a valid timezone, valid timezones are one of:

  • TimezoneInfo struct
  • A timezone name as a string
  • :utc as a shortcut for the UTC timezone
  • :local as a shortcut for the local timezone
  • A number representing an offset from UTC

Return a 3-tuple {year, week number, weekday} for the given Date/DateTime.

Examples

iex> Elixir.Timex.iso_triplet(Timex.epoch)
{1970, 1, 4}

Return a pair {year, week number} (as defined by ISO 8601) that the given Date/DateTime value falls on.

Examples

iex> Elixir.Timex.iso_week({1970, 1, 1})
{1970,1}

Same as iso_week/1, except this takes a year, month, and day as distinct arguments.

Examples

iex> Elixir.Timex.iso_week(1970, 1, 1)
{1970,1}
Link to this function lformat(datetime, format_string, locale) View Source
lformat(
  Timex.Types.valid_datetime(),
  format :: String.t(),
  locale :: String.t()
) :: {:ok, String.t()} | {:error, term()}

Same as format/2, except takes a locale name to translate text to.

Translations only apply to units, relative time phrases, and only for the locales in the list of supported locales in the Timex documentation.

Link to this function lformat(datetime, format_string, locale, formatter) View Source
lformat(
  Timex.Types.valid_datetime(),
  format :: String.t(),
  locale :: String.t(),
  formatter :: atom()
) :: {:ok, String.t()} | {:error, term()}

Same as lformat/3, except takes a formatter as it’s last argument.

Translations only apply to units, relative time phrases, and only for the locales in the list of supported locales in the Timex documentation.

Link to this function lformat!(datetime, format_string, locale) View Source
lformat!(
  Timex.Types.valid_datetime(),
  format :: String.t(),
  locale :: String.t()
) :: String.t() | no_return()

Same as lformat/3, except local_format! raises on error.

See lformat/3 docs for usage examples.

Link to this function lformat!(datetime, format_string, locale, formatter) View Source
lformat!(
  Timex.Types.valid_datetime(),
  format :: String.t(),
  locale :: String.t(),
  formatter :: atom()
) :: String.t() | no_return()

Same as lformat/4, except local_format! raises on error.

See lformat/4 docs for usage examples

Link to this function lformat_duration(timestamp, locale) View Source
lformat_duration(Timex.Duration.t(), locale :: String.t()) ::
  String.t() | {:error, term()}

Same as format_duration/1, except takes a locale for use in translation

Link to this function lformat_duration(timestamp, locale, formatter) View Source
lformat_duration(Timex.Duration.t(), locale :: String.t(), atom()) ::
  String.t() | {:error, term()}

Same as lformat_duration/2, except takes a formatter as an argument

Returns a DateTime representing the current moment in time in the local timezone.

Returns a DateTime representing the given date/time in the local timezone

Link to this function month_name(num) View Source
month_name(Timex.Types.month()) :: String.t() | {:error, :invalid_month_number}

Get the name of the month corresponding to the provided number

Examples

iex> Elixir.Timex.month_name(1)
"January"
iex> Elixir.Timex.month_name(0)
{:error, :invalid_month_number}
Link to this function month_shortname(num) View Source
month_shortname(Timex.Types.month()) ::
  String.t() | {:error, :invalid_month_number}

Get the short name of the month corresponding to the provided number

Examples

iex> Elixir.Timex.month_shortname(1)
"Jan"
iex> Elixir.Timex.month_shortname(0)
{:error, :invalid_month_number}
Link to this function month_to_num(arg1) View Source
month_to_num(binary()) :: integer() | {:error, :invalid_month_name}

Get the number of the month corresponding to the given name.

Examples

iex> Elixir.Timex.month_to_num("January")
1
iex> Elixir.Timex.month_to_num("january")
1
iex> Elixir.Timex.month_to_num("Jan")
1
iex> Elixir.Timex.month_to_num("jan")
1
iex> Elixir.Timex.month_to_num(:jan)
1
Link to this function normalize(atom, year) View Source
normalize(:date, {integer(), integer(), integer()}) :: Timex.Types.date()
normalize(
  :time,
  {integer(), integer(), integer()}
  | {integer(), integer(), integer(), integer()}
) :: Timex.Types.time()
normalize(:day, {integer(), integer(), integer()}) :: non_neg_integer()
normalize(
  :year
  | :month
  | :day
  | :hour
  | :minute
  | :second
  | :millisecond
  | :microsecond,
  integer()
) :: non_neg_integer()

Given a unit to normalize, and the value to normalize, produces a valid value for that unit, clamped to whatever boundaries are defined for that unit.

Example

iex> Timex.normalize(:hour, 26)
23

Returns a DateTime representing the current moment in time in UTC

Returns a DateTime representing the current moment in time in the provided timezone.

Link to this function parse(datetime_string, format_string) View Source
parse(String.t(), String.t()) ::
  {:ok, DateTime.t() | NaiveDateTime.t()} | {:error, term()}

Parses a datetime string into a DateTime struct, using the provided format string (and optional tokenizer).

See Timex.Format.DateTime.Formatters.Default or Timex.Format.DateTime.Formatters.Strftime for documentation on the syntax supported in format strings by their respective tokenizers.

To use the Default tokenizer, simply call parse/2. To use the Strftime tokenizer, you can either alias and pass Timex.Parse.DateTime.Tokenizer.Strftime by module name, or as a shortcut, you can pass :strftime instead.

Examples

iex> use Timex
...> {:ok, result} = Timex.parse("2016-02-29", "{YYYY}-{0M}-{D}")
...> result
~N[2016-02-29T00:00:00]

iex> use Timex
...> expected = Timex.to_datetime({{2016, 2, 29}, {22, 25, 0}}, "America/Chicago")
...> {:ok, result} = Timex.parse("2016-02-29T22:25:00-06:00", "{ISO:Extended}")
...> Timex.equal?(expected, result)
true

iex> use Timex
...> expected = Timex.to_datetime({{2016, 2, 29}, {22, 25, 0}}, "America/Chicago")
...> {:ok, result} = Timex.parse("2016-02-29T22:25:00-06:00", "%FT%T%:z", :strftime)
...> Timex.equal?(expected, result)
true
Link to this function parse(datetime_string, format_string, tokenizer) View Source
parse(String.t(), String.t(), atom()) ::
  {:ok, DateTime.t() | NaiveDateTime.t()} | {:error, term()}
Link to this function parse!(datetime_string, format_string) View Source

Same as parse/2 and parse/3, except parse! raises on error.

See parse/2 or parse/3 docs for usage examples.

Link to this function parse!(datetime_string, format_string, tokenizer) View Source
parse!(String.t(), String.t(), atom()) ::
  DateTime.t() | NaiveDateTime.t() | no_return()

Returns what quarter of the year the given date/time falls in.

Examples

iex> Timex.quarter(4)
2

Return a new date/time value with the specified fields replaced by new values.

Values are automatically validated and clamped to good values by default. If you wish to skip validation, perhaps for performance reasons, pass validate: false.

Values are applied in order, so if you pass [datetime: dt, date: d], the date value from date will override datetime’s date value.

Options which do not apply to the input value (for example, :hour against a Date struct), will be ignored.

Example

iex> use Timex
...> expected = ~D[2015-02-28]
...> result = Timex.set(expected, [month: 2, day: 30])
...> result == expected
true

iex> use Timex
...> expected = ~N[2016-02-29T23:30:00]
...> result = Timex.set(expected, [hour: 30])
...> result === expected
true

A single function for adjusting the date using various units: duration, microseconds, seconds, minutes, hours, days, weeks, months, years.

The result of applying the shift will be the same type as that of the input, with the exception of shifting DateTimes, which may result in an AmbiguousDateTime if the shift moves to an ambiguous time period for the zone of that DateTime.

If an error occurs, an error tuple will be returned.

Examples

Shifting across timezone changes

iex> use Timex
...> datetime = Timex.to_datetime({{2016,3,13}, {1,0,0}}, "America/Chicago")
...> # 2-3 AM doesn't exist
...> shifted = Timex.shift(datetime, hours: 1)
...> {datetime.zone_abbr, shifted.zone_abbr, shifted.hour}
{"CST", "CDT", 3}

Shifting into an ambiguous time period

iex> use Timex
...> datetime = Timex.to_datetime({{1895,12,31}, {0,0,0}}, "Asia/Taipei")
...> %AmbiguousDateTime{} = expected = Timex.to_datetime({{1895,12,31}, {23,55,0}}, "Asia/Taipei")
...> expected == Timex.shift(datetime, hours: 23, minutes: 53, seconds: 120)
true

Shifting and leap days

iex> use Timex
...> date = ~D[2016-02-29]
...> Timex.shift(date, years: -1)
~D[2015-02-28]

Called when an application is started.

This function is called when an application is started using Application.start/2 (and functions on top of that, such as Application.ensure_started/2). This function should start the top-level process of the application (which should be the top supervisor of the application’s supervision tree if the application follows the OTP design principles around supervision).

start_type defines how the application is started:

  • :normal - used if the startup is a normal startup or if the application is distributed and is started on the current node because of a failover from another node and the application specification key :start_phases is :undefined.
  • {:takeover, node} - used if the application is distributed and is started on the current node because of a failover on the node node.
  • {:failover, node} - used if the application is distributed and is started on the current node because of a failover on node node, and the application specification key :start_phases is not :undefined.

start_args are the arguments passed to the application in the :mod specification key (e.g., mod: {MyApp, [:my_args]}).

This function should either return {:ok, pid} or {:ok, pid, state} if startup is successful. pid should be the PID of the top supervisor. state can be an arbitrary term, and if omitted will default to []; if the application is later stopped, state is passed to the stop/1 callback (see the documentation for the c:stop/1 callback for more information).

use Application provides no default implementation for the start/2 callback.

Callback implementation for Application.start/2.

Subtract time from a date using a Duration Same as shift(date, Duration.from_minutes(5) |> Duration.invert, :timestamp).

Get a TimezoneInfo object for the specified offset or name.

When offset or name is invalid, exception is raised.

If no DateTime value is given for the second parameter, the current date/time will be used (in other words, it will return the current timezone info for the given zone). If one is provided, the timezone info returned will be based on the provided DateTime (or Erlang datetime tuple) value.

Examples

iex> date = Timex.to_datetime({2015, 4, 12})
...> tz = Timex.timezone(:utc, date)
...> tz.full_name
"Etc/UTC"

iex> tz = Timex.timezone("America/Chicago", {2015,4,12})
...> {tz.full_name, tz.abbreviation}
{"America/Chicago", "CDT"}

iex> tz = Elixir.Timex.timezone(+2, {2015, 4, 12})
...> {tz.full_name, tz.abbreviation}
{"Etc/GMT-2", "+02"}
Link to this function timezones() View Source
timezones() :: [String.t()]

Returns a list of all valid timezone names in the Olson database

Convert a date/time value to a Date struct.

Link to this function to_datetime(from) View Source
to_datetime(Timex.Types.valid_datetime()) :: DateTime.t() | {:error, term()}

Convert a date/time value and timezone name to a DateTime struct. If the DateTime is ambiguous and cannot be resolved, an AmbiguousDateTime will be returned, allowing the developer to choose which of the two choices is desired.

If no timezone is provided, “Etc/UTC” will be used

Convert a date/time value to it’s Erlang representation

Link to this function to_gregorian_microseconds(datetime) View Source
to_gregorian_microseconds(Timex.Types.valid_datetime()) ::
  non_neg_integer() | {:error, term()}

Convert a date/time value to gregorian microseconds (microseconds since start of year zero)

Link to this function to_gregorian_seconds(datetime) View Source
to_gregorian_seconds(Timex.Types.valid_datetime()) ::
  non_neg_integer() | {:error, term()}

Convert a date/time value to gregorian seconds (seconds since start of year zero)

Link to this function to_julian(datetime) View Source
to_julian(Timex.Types.valid_datetime()) :: integer() | {:error, term()}

Convert a date/time value to a Julian calendar date number

Link to this function to_naive_datetime(date) View Source
to_naive_datetime(Timex.Types.valid_datetime()) ::
  NaiveDateTime.t() | {:error, term()}

Convert a date/time value to a NaiveDateTime struct.

Convert a date/time value to seconds since the UNIX epoch

Returns a Date representing the current day in UTC

Link to this function validate_format(format_string) View Source
validate_format(String.t()) :: :ok | {:error, term()}

Given a format string, validates that the format string is valid for the Default formatter.

Given a format string and a formatter, validates that the format string is valid for that formatter.

Examples

iex> use Timex
...> Timex.validate_format("{YYYY}-{M}-{D}")
:ok

iex> use Timex
...> Timex.validate_format("{YYYY}-{M}-{V}")
{:error, "Expected end of input at line 1, column 11"}

iex> use Timex
...> Timex.validate_format("%FT%T%:z", :strftime)
:ok
Link to this function validate_format(format_string, formatter) View Source
validate_format(String.t(), atom()) :: :ok | {:error, term()}

Returns the week number of the date provided, starting at 1.

Examples

iex> Timex.week_of_month(~D[2016-03-05])
1

iex> Timex.week_of_month(~N[2016-03-14T00:00:00Z])
3

Same as week_of_month/1, except takes year, month, and day as distinct arguments

Examples

iex> Timex.week_of_month(2016, 3, 30)
5

Return weekday number (as defined by ISO 8601) of the specified date.

Examples

iex> Timex.epoch |> Elixir.Timex.weekday
4 # (i.e. Thursday)

Returns a Date representing the start of the Gregorian epoch