timex v2.1.3 Timex
Timex
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 2.x
See the Migrating section further down for details.
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, "~> x.x.x"}]
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
> date = Date.today
%Date{year: 2016, month: 2, day: 29}
> datetime = DateTime.today
%DateTime{year: 2016, month: 2, day: 29,
hour: 12, minute: 30, second: 30, millisecond: 120, timezone: %TimezoneInfo{...}}
> timestamp = Time.now
{1457, 137754, 906908}
> default_str = Timex.format(datetime, "{ISO:Extended}")
{:ok, "2016-02-29T12:30:30.120+00:00"}
> strftime_str = Timex.format(datetime, "%FT%T%:z", :strftime)
{:ok, "2016-02-29T12:30:30+00:00"}
> Timex.parse(default_str, "{ISO:Extended}")
{:ok, %DateTime{...}}
> Timex.parse(strftime_str, "%FT%T%:z", :strftime)
{:ok, %DateTime{...}}
> Time.diff(Time.now, Time.zero, :days)
16850
> Timex.shift(date, days: 3)
%Date{year: 2016, month: 3, day: 3}
> Timex.shift(date, hours: 2, minutes: 13)
%DateTime{year: 2016, month: 2, day: 29,
hour: 14, minute: 43, second: 30, millisecond: 120, timezone: %TimezoneInfo{...}}
> timezone = Timex.timezone("America/Chicago", DateTime.today)
%Timex.TimezoneInfo{abbreviation: "CST",
from: {:sunday, {{2015, 11, 1}, {1, 0, 0}}}, full_name: "America/Chicago",
offset_std: 0, offset_utc: -360, until: {:sunday, {{2016, 3, 13}, {2, 0, 0}}}}
> Timezone.convert(datetime, timezone)
%DateTime{year: 2016, month: 2, day: 29,
hour: 6, minute: 30, second: 30, millisecond: 120,
timezone: %TimezoneInfo{abbreviation: "CST", ...}}
> Timex.equal?(Date.today, DateTime.today)
true
> Timex.before?(Date.today, Timex.shift(Date.today, days: 1))
true
There are a ton of other functions for Dates, Times, and DateTimes, way more than can be covered here. Hopefully the above gives you a taste of what the API is like!
Extensibility
Timex exposes a number of extension points for you, in order to accomodate different use cases:
You can use custom Date/DateTime types with Timex via the Timex.Convertable
protocol, which gives you a way to convert your type to various Timex types, and then use the Timex API to manipulate them, for example, you could use the Calendar library’s types with Timex via Comparable, or Ecto’s, or your own!
You can compare/diff custom Date/DateTime types with Timex via the Timex.Comparable
protocol, which also understands types which implement Timex.Convertable
, allowing you to use Comparable as soon as you’ve implemented Convertable!
The same is true for Timex’s API in general - if you pass a type which implements Timex.Convertable
, and the type is not a native Timex one, it will be coerced to one via that protocol.
You can provide your own formatter/parser for Date/DateTime strings by implementing the Timex.Format.DateTime.Formatter
and/or Timex.Parse.DateTime.Parser
behaviours, depending on your needs.
Common Issues
Warning: 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 occured before, and it’s important to note this!
- 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.
Migrating
If you have been using Timex pre-2.x, and you are looking to migrate, it’s fairly painless, but important to review the list of breaking changes and new features.
Overview of 2.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 2.x. I promise it’s easy!
- There are now three date types:
Date
,DateTime
, andAmbiguousDateTime
. The first two are pretty obvious, but to recap: - If you are working with dates and don’t care about time information - use
Date
- For everything else, use
DateTime
AmbiguousDateTime
is returned in cases where timezone information is ambiguous for a given point in time. The struct has two fieldsbefore
andafter
, containingDateTime
structs to choose from, based on what your intent is. It is up to you to choose one, or raise an error if you aren’t sure what do to.- To accompany
AmbiguousDateTime
there is alsoAmbiguousTimezoneInfo
, which is almost the same thing, except it’s fields containTimezoneInfo
structs to choose from. This one is used mostly internally, but if you useTimezone.get
, you’ll need to plan for this. - All functions which are not specific to a given date type, are now found under the Timex module itself, all functions which
are shared or common between
Date
andDateTime
can also be found underTimex
and it will delegate to the appropriate module, this should make it easier to useDate
andDateTime
together without having to remember which API to call for a specific value, Timex will just do the right thing for you. Timex.Date
andTimex.DateTime
expose APIs specific to those types,Timex.DateTime
is effectively the older API you are familiar with from pre-2.x Timex. Timex.Date is no longer the main API module, use Timex- Date/DateTime formatting and parsing APIs are exposed via the
Timex
module, but the old formatter and parser modules are still there, the exception being DateFormat, which has been removed, if you were using it, change to Timex. - Date/DateTime/Erlang datetime tuple/etc. common conversions are now exposed via the
Timex.Convertable
protocol. Implementations for those types are already included. Timex.Date.Convert is removed, as well as the DateConvert alias, use Timex.Convertable instead
There was a significant amount of general project improvements done as part of this release as well:
- Shifting dates/times is now far more accurate, and more flexible than it was previously, shifting across leaps, timezone changes, and non-existent time periods are now all fully supported
- The API does a much better job of validation and is strict about inputs, and because all APIs now return error tuples instead of raising exceptions, it is much easier to handle gracefully.
- The code has been reorganized into a more intuitive structure
- Fixed typespecs, docs, and tests across the board
- Almost 100 more tests, with more to come
- Cleaned up dirty code along the way (things like single-piping, inconsistent parens, etc.)
Migration steps (1.x -> 2.x)
Depending on how heavily you are using the various features of Timex’s API, the migration can be anywhere from 15 minutes to a couple of hours, but the steps below are a guide which should help the process go smoothly. For the vast majority of folks, I anticipate that it will be a very small time investment.
- Change all
Timex.Date
references toTimex
, except those which are creatingDateTime
values, such asDate.now
, those references should be changed to point toDateTime
now. - Change all
DateFormat
references toTimex
,DateFormat
was removed. - Change all
Timex.Date.Convert
orDateConvert
references toTimex
orTimex.Convertable
, the former have become the latter - Make sure you upgrade
timex_ecto
as well if you are using it with your project - Compile, if you get warnings about missing methods on
Timex
, they are type-specific functions forDateTime
, so change those references toTimex.DateTime
- You’ll need to modify your code to handle error tuples instead of exceptions
- You’ll need to handle the new
AmbiguousDateTime
andAmbiguousTimezoneInfo
structs, the best approach is to pattern match on API return values, useDateTime
if it was given, or select:before
or:after
values from theAmbiguous*
structs. Your code will become a lot safer as a result of this change! - Unit names are soft-deprecated for now, but you’ll want to change references to abbreviated units like
secs
to their full names (i.e.seconds
) in order to make the stderr warnings go away.
And that’s it! If you have any issues migrating, please ping me, and I’ll be glad to help. If you have a dependency that uses Timex which you’d like to get updated to 2.x, open an issue here, and I’ll submit a PR to those projects to help bring them up to speed quicker.
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)
- Locale-aware formatting/parsing (a relatively high priority)
{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
, andtimeFrom
formatting functions. - Calendar time formatter/parser, along the lines of Moment.js’s calendar time formatter
- Richer duration support via the
Interval
module - Recurring dates/times API
- Support for calendars other than Gregorian (e.g. Julian)
License
This software is licensed under the MIT license.
Summary
Functions
Add time to a date using a timestamp, i.e. {megasecs, secs, microsecs} Same as shift(date, Time.to_timestamp(5, :minutes), :timestamp)
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
Same as beginning_of_year, except takes an integer year + timezone as arguments
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
Creates a new Date value, which represents the first day of year zero
Creates a new DateTime value, which represents the first moment of the first day of year zero
Same as datetime/1
, except this version returns a DateTime or AmbiguousDateTime in the provided timezone
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 always be a non-negative integer
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
Same as end_of_year/1, except takes an integer year + timezone as arguments
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,
not equality of the data structure
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_time/1, except it also accepts a formatter
WARNING: Added to ease the migration to 2.x, but it is deprecated
WARNING: Added to ease the migration to 2.x, but it is deprecated.
Use Timex.date/1 or Timex.datetime/2 instead
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_time/1, except takes a locale for use in translation
Same as lformat_time/2, except takes a formatter as an argument
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
Produces a valid Date or DateTime object based on a date or datetime tuple respectively
Like normalize/1, but for specific types of values
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
Return a new Date/DateTime with the specified fields replaced by new values
A single function for adjusting the date using various units: timestamp, milliseconds, seconds, minutes, hours, days, weeks, months, years
Subtract time from a date using a timestamp, i.e. {megasecs, secs, microsecs} Same as shift(date, Time.to_timestamp(5, :minutes) |> Time.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 to a DateTime struct
Convert a date/time value to a standard Erlang datetme tuple. i.e. { {year, month, day}, {hour, minute, second} }
Convert a date/time value to a Gregorian calendar datetme+timezone tuple. i.e. { {year, month, day}, {hour, minute, second}, {offset_hours, timezone_abbreviation}}
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 an Erlang timestamp
Convert a date/time value to seconds since the UNIX epoch
Given a format string, validates that the format string is valid for the Default formatter
Given a Convertable, this function 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
Functions
Specs
add(Timex.Convertable, Timex.Types.timestamp) ::
Timex.DateTime.t |
{:error, term}
Add time to a date using a timestamp, i.e. {megasecs, secs, microsecs} Same as shift(date, Time.to_timestamp(5, :minutes), :timestamp).
Specs
after?(Timex.Comparable.comparable, Timex.Comparable.comparable) ::
boolean |
{:error, term}
Returns a boolean indicating whether the first Timex.Comparable
occurs after the second
Specs
before?(Timex.Comparable.comparable, Timex.Comparable.comparable) ::
boolean |
{:error, term}
Returns a boolean indicating whether the first Timex.Comparable
occurs before the second
Specs
beginning_of_day(Timex.Convertable) ::
Timex.DateTime.t |
{:error, term}
Returns a DateTime representing the beginning of the day
Examples
iex> date = Timex.datetime({{2015, 1, 1}, {13, 14, 15}})
iex> Timex.beginning_of_day(date)
Timex.datetime({{2015, 1, 1}, {0, 0, 0}})
iex> date = Timex.date({{2015, 1, 1}, {13, 14, 15}})
...> Timex.beginning_of_day(date)
Timex.date({{2015,1,1}, {0,0,0}})
Specs
beginning_of_month(Timex.Date.t | Timex.DateTime.t | Timex.Comparable) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date returns a date at the beginning of the month.
iex> date = Timex.datetime({{2015, 6, 15}, {12,30,0}}, “Europe/Paris”) iex> Elixir.Timex.beginning_of_month(date) Timex.datetime({{2015, 6, 1}, {0, 0, 0}}, “Europe/Paris”)
Specs
beginning_of_month(Timex.Types.year, Timex.Types.month) ::
Timex.Date.t |
{:error, term}
Same as beginning_of_month/1, except takes year and month as distinct arguments
Specs
beginning_of_quarter(Timex.Date.t | Timex.Convertable) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date returns a date at the beginning of the quarter.
iex> date = Timex.datetime({{2015, 6, 15}, {12,30,0}}, “CST”) iex> Timex.beginning_of_quarter(date) Timex.datetime({{2015, 4, 1}, {0, 0, 0}}, “CST”)
Specs
beginning_of_week(Timex.Types.valid_datetime, Timex.Types.weekday) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
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 = Timex.datetime({{2015, 11, 30}, {13, 30, 30}}) # Monday 30th November
iex> Timex.beginning_of_week(date)
Timex.datetime({2015, 11, 30})
iex> date = Timex.date({{2015, 11, 30}, {13, 30, 30}}) # Monday 30th November
iex> Timex.beginning_of_week(date, :sun)
Timex.date({2015, 11, 29})
Specs
beginning_of_year(Timex.Date.t | Timex.Comparable | Timex.Types.year) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date or a number create a date at the beginning of that year
Examples
iex> date = Timex.datetime({{2015, 6, 15}, {0, 0, 0, 0}})
iex> Timex.beginning_of_year(date)
Timex.datetime({{2015, 1, 1}, {0, 0, 0, 0}})
iex> Timex.beginning_of_year(2015)
Timex.date({{2015, 1, 1}, {0, 0, 0, 0}})
iex> Timex.beginning_of_year(2015, "Europe/London")
Timex.datetime({{2015, 1, 1}, {0, 0, 0, 0}}, "Europe/London")
Specs
beginning_of_year(Timex.Types.year, Timex.Types.valid_timezone) ::
Timex.DateTime.t |
{:error, term}
Same as beginning_of_year, except takes an integer year + timezone as arguments.
Specs
between?(Timex.Comparable.comparable, Timex.Comparable.comparable, Timex.Comparable.comparable) ::
boolean |
{:error, term}
Returns a boolean indicating whether the first Timex.Comparable
occurs between the second and third
Specs
century :: non_neg_integer
Gets the current century
Examples
iex> Elixir.Timex.century 21
Specs
century(Timex.Convertable | Timex.Types.year) ::
non_neg_integer |
{:error, term}
Given a date, get the century this date is in.
Examples
iex> Timex.Date.today |> Elixir.Timex.century 21 iex> Timex.DateTime.now |> Elixir.Timex.century 21 iex> Elixir.Timex.century(2016) 21
Specs
compare(Timex.Comparable.comparable, Timex.Comparable.comparable) ::
Timex.Comparable.compare_result |
{:error, term}
See docs for compare/3
Specs
compare(Timex.Comparable.comparable, Timex.Comparable.comparable, Timex.Comparable.granularity) ::
Timex.Comparable.compare_result |
{:error, term}
Compare two Timex.Comparable
values, returning one of the following values:
-1
— the first date comes before the second one0
— 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
- :timestamp
and the dates will be compared with the cooresponding accuracy. The default granularity is :seconds.
Examples
iex> date1 = Timex.date({2014, 3, 4})
iex> date2 = Timex.date({2015, 3, 4})
iex> Timex.compare(date1, date2, :years)
-1
iex> Timex.compare(date2, date1, :years)
1
iex> Timex.compare(date1, date1)
0
Specs
date(Timex.Convertable) ::
Timex.Date.t |
{:error, term}
Creates a new Date value, which represents the first day of year zero.
If a date/time value is provided, it will convert it to a Date struct.
Specs
datetime(Timex.Convertable) ::
Timex.DateTime.t |
{:error, term}
Creates a new DateTime value, which represents the first moment of the first day of year zero.
The provided date/time value will be converted via the Timex.Convertable
protocol.
Specs
datetime(Timex.Convertable, Timex.Types.valid_timezone) ::
Timex.DateTime.t |
Timex.AmbiguousDateTime.t |
{:error, term}
Same as datetime/1
, except this version returns a DateTime or AmbiguousDateTime in the provided timezone.
Specs
day(Timex.Convertable) ::
Timex.Types.daynum |
{:error, term}
Returns the ordinal day number of the date.
Examples
iex> Timex.datetime({{2015,6,26},{0,0,0}}) |> Timex.day 177
Specs
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}
Specs
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}
Specs
day_to_num(binary | atom) ::
integer |
{:error, :invalid_day_name}
Get the day of the week corresponding to the given name.
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
Specs
days_in_month(Timex.Convertable) ::
Timex.Types.num_of_days |
{:error, term}
Return the number of days in the month which the date falls on.
Examples
iex> Timex.Date.epoch |> Timex.days_in_month
31
Specs
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
Specs
days_to_beginning_of_week(Timex.Types.valid_datetime, Timex.Types.weekday) ::
integer |
{:error, term}
Number of days to the beginning 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 = Timex.datetime({2015, 11, 30}) # Monday 30th November
iex> Timex.days_to_beginning_of_week(date)
0
Week starting Sunday
iex> date = Timex.date({2015, 11, 30}) # Monday 30th November
iex> Timex.days_to_beginning_of_week(date, :sun)
1
Specs
days_to_end_of_week(Timex.Convertable, Timex.Types.weekday) ::
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 = Timex.datetime({2015, 11, 30}) # Monday 30th November
iex> Timex.days_to_end_of_week(date)
6
Week starting Sunday
iex> date = Timex.date({2015, 11, 30}) # Monday 30th November
iex> Timex.days_to_end_of_week(date, :sun)
5
Specs
diff(Timex.Comparable.comparable, Timex.Comparable.comparable) ::
Timex.Types.timestamp |
{:error, term}
See docs for diff/3
Specs
diff(Timex.Comparable.comparable, Timex.Comparable.comparable, Timex.Comparable.granularity) ::
Timex.Types.timestamp |
non_neg_integer |
{:error, term}
Calculate time interval between two dates. The result will always be a non-negative integer
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
- :timestamp
and the result will be an integer value of those units or a timestamp.
Specs
end_of_day(Timex.Convertable) ::
Timex.DateTime.t |
{:error, term}
Returns a DateTime representing the end of the day
Examples
iex> date = Timex.datetime({{2015, 1, 1}, {13, 14, 15}})
...> Timex.end_of_day(date)
Timex.datetime({{2015, 1, 1}, {23, 59, 59}})
iex> date = Timex.date({{2015, 1, 1}, {13, 14, 15}})
...> Timex.end_of_day(date)
Timex.date({{2015,1,1}, {23,59,59}})
Specs
end_of_month(Timex.Date.t | Timex.DateTime.t) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date returns a date at the end of the month.
iex> date = Timex.datetime({{2015, 6, 15}, {12, 30, 0}}, “Europe/London”) iex> Timex.end_of_month(date) Timex.datetime({{2015, 6, 30}, {23, 59, 59}}, “Europe/London”)
Specs
end_of_month(Timex.Types.year, Timex.Types.month) :: Timex.Date.t
Same as end_of_month/1, except takes year and month as distinct arguments
Examples
iex> Timex.end_of_month(2016, 2)
Timex.date({2016, 2, 29})
Specs
end_of_quarter(Timex.Convertable) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date or a year and month returns a date at the end of the quarter.
iex> date = Timex.datetime({{2015, 6, 15}, {12,30,0}}, “CST”) iex> Timex.end_of_quarter(date) Timex.datetime({{2015, 6, 30}, {23, 59, 59}}, “CST”)
iex> Timex.end_of_quarter(2015, 4) Timex.date({{2015, 6, 30}, {23, 59, 59}})
Specs
end_of_quarter(Timex.Types.year, Timex.Types.month) ::
Timex.Date.t |
{:error, term}
Same as end_of_quarter/1, except takes year and month as distinct arguments
Specs
end_of_week(Timex.Convertable, Timex.Types.weekday) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
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 = Timex.datetime({{2015, 11, 30}, {13, 30, 30}}) # Monday 30th November
...> Timex.end_of_week(date)
Timex.datetime({{2015, 12, 6}, {23, 59, 59}})
iex> date = Timex.date({{2015, 11, 30}, {13, 30, 30}}) # Monday 30th November
...> Timex.end_of_week(date, :sun)
Timex.date({2015, 12, 5})
Specs
end_of_year(Timex.Date.t | Timex.Types.year | Timex.Comparable) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Given a date or a number create a date at the end of that year
Examples
iex> date = Timex.datetime({{2015, 6, 15}, {0, 0, 0, 0}})
iex> Timex.end_of_year(date)
Timex.datetime({{2015, 12, 31}, {23, 59, 59}})
iex> Timex.end_of_year(2015)
Timex.date({{2015, 12, 31}, {23, 59, 59}})
iex> Timex.end_of_year(2015, "Europe/London")
Timex.datetime {{2015, 12, 31}, {23, 59, 59}}, "Europe/London"
Specs
end_of_year(Timex.Types.year, Timex.Types.valid_timezone) ::
Timex.DateTime.t |
{:error, term}
Same as end_of_year/1, except takes an integer year + timezone as arguments
Specs
equal?(Timex.Date.t | Timex.DateTime.t, Timex.Date.t | Timex.DateTime.t) ::
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,
not equality of the data structure.
Examples
iex> date1 = Timex.date({2014, 3, 1})
...> date2 = Timex.date({2014, 3, 1})
...> Elixir.Timex.equal?(date1, date2)
true
iex> date1 = Timex.date({2014, 3, 1})
...> date2 = Timex.datetime({2014, 3, 1})
...> Elixir.Timex.equal?(date1, date2)
true
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 uses the Convertable protocol to convert non-DateTime structs to DateTime structs.
Examples
iex> date = Timex.date({2016, 2, 29})
...> Timex.format!(date, "{YYYY}-{0M}-{D}")
"2016-02-29"
iex> Timex.format!({{2016,2,29},{22,25,0}}, "{ISO:Extended}")
"2016-02-29T22:25:00+00:00"
Specs
Same as format/2, except using a custom formatter
Examples
iex> use Timex
...> datetime = Timex.datetime({{2016,2,29},{22,25,0}}, "America/Chicago")
iex> Timex.format!(datetime, "%FT%T%:z", :strftime)
"2016-02-29T22:25:00-06:00"
Same as format/2, except format! raises on error.
See format/2 docs for usage examples.
Same as format/3, except format! raises on error.
See format/3 docs for usage examples
Specs
format_time(Timex.Types.timestamp) ::
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.Time.Formatters.Default or Timex.Format.Time.Formatters.Humanized for documentation on the specific formatter behaviour.
To use the Default formatter, simply call format_time/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
...> date = Date.to_timestamp(Timex.date({2016, 2, 29}), :epoch)
...> Timex.format_time(date)
"P46Y2M10D"
iex> use Timex
...> date = Date.to_timestamp(Timex.date({2016, 2, 29}), :epoch)
...> Timex.format_time(date, :humanized)
"46 years, 2 months, 1 week, 3 days"
iex> use Timex
...> datetime = Timex.datetime({{2016, 2, 29}, {22, 25, 0}}) |> DateTime.to_timestamp
...> Timex.format_time(datetime, :humanized)
"46 years, 2 months, 1 week, 3 days, 22 hours, 25 minutes"
Specs
format_time(Timex.Types.timestamp, atom) ::
String.t |
{:error, term}
Same as format_time/1, except it also accepts a formatter
WARNING: Added to ease the migration to 2.x, but it is deprecated.
Returns a DateTime, like the old Date.from/1
API
WARNING: Added to ease the migration to 2.x, but it is deprecated.
Use Timex.date/1 or Timex.datetime/2 instead.
Returns a DateTime, like the old Date.from/2
API
Specs
from_iso_day(non_neg_integer) ::
Timex.Date.t |
{:error, term}
Convert an iso ordinal day number to the day it represents in the current year.
## Examples
iex> use Timex
iex> %Date{:year => year} = Timex.from_iso_day(180)
...> %Date{:year => todays_year} = Date.today
...> year == todays_year
true
Specs
from_iso_day(non_neg_integer, Timex.Types.year | Timex.Date.t | Timex.DateTime.t | Timex.Convertable) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
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
- If a Date struct is given, the result will be a Date struct
- If a DateTime struct is given, the result will be a DateTime struct
- If a Convertable is given, the result will be a DateTime struct
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 = Timex.date({2015, 6, 29})
...> (expected === Timex.from_iso_day(180, 2015))
true
Creating a Date/DateTime from the given day
iex> use Timex
...> expected = Timex.datetime({{2015, 6, 29}, {0,0,0}})
...> (expected === Timex.from_iso_day(180, Timex.datetime({{2015,1,1}, {0,0,0}})))
true
Shifting a Date/DateTime to the given day
iex> use Timex
...> date = Timex.datetime({{2015,6,26}, {12,0,0}})
...> expected = Timex.datetime({{2015, 6, 29}, {12,0,0}})
...> (Timex.from_iso_day(180, date) === expected)
true
Specs
from_iso_triplet(Timex.Types.iso_triplet) ::
Timex.Date.t |
{:error, term}
Given an ISO triplet {year, week number, weekday}
, convert it to a Date struct.
Examples
iex> expected = Timex.date({2014, 1, 28})
iex> Timex.from_iso_triplet({2014, 5, 2}) === expected
true
Specs
from_now(Timex.Convertable) ::
String.t |
{:error, term}
Formats a DateTime using a fuzzy relative duration, from now.
Examples
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.now, days: 2))
"in 2 days"
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.now, days: -2))
"2 days ago"
Specs
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
Specs
is_leap?(Timex.Types.valid_datetime | Timex.Types.year) ::
boolean |
{:error, term}
Return a boolean indicating whether the given year is a leap year. You may pase a date or a year number.
Examples
iex> DateTime.epoch |> Elixir.Timex.is_leap?
false
iex> Elixir.Timex.is_leap?(2012)
true
Specs
is_valid?(Timex.Convertable) :: boolean
Return a boolean indicating whether the given date is valid.
Examples
iex> use Timex
...> Timex.is_valid?({{1,1,1},{1,1,1}})
true
iex> use Timex
...> %DateTime{} |> Elixir.Timex.set([month: 13, validate: false]) |> Elixir.Timex.is_valid?
false
iex> use Timex
...> %DateTime{} |> Elixir.Timex.set(hour: -1) |> Elixir.Timex.is_valid?
false
Specs
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}
Specs
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
Specs
iso_triplet(Timex.Convertable) ::
{Timex.Types.year, Timex.Types.weeknum, Timex.Types.weekday} |
{:error, term}
Return a 3-tuple {year, week number, weekday} for the given Date/DateTime.
Examples
iex> Elixir.Timex.iso_triplet(Timex.DateTime.epoch)
{1970, 1, 4}
Specs
iso_week(Timex.Convertable) ::
{Timex.Types.year, Timex.Types.weeknum} |
{:error, term}
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}
Specs
iso_week(Timex.Types.year, Timex.Types.month, Timex.Types.day) ::
{Timex.Types.year, Timex.Types.weeknum} |
{:error, term}
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}
Specs
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.
Specs
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.
Same as lformat/3, except local_format! raises on error.
See lformat/3 docs for usage examples.
Specs
Same as lformat/4, except local_format! raises on error.
See lformat/4 docs for usage examples
Same as format_time/1, except takes a locale for use in translation
Same as lformat_time/2, except takes a formatter as an argument
Specs
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}
Specs
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_name(1)
"January"
iex> Elixir.Timex.month_name(0)
{:error, :invalid_month_number}
Specs
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
Specs
normalize(Timex.Types.valid_datetime) ::
Timex.Date.t |
Timex.DateTime.t |
{:error, term}
Produces a valid Date or DateTime object based on a date or datetime tuple respectively.
All date’s components will be clamped to the minimum or maximum valid value.
Examples
iex> use Timex …> localtz = Timezone.local({{1,12,31},{0,59,59}}) …> Timex.normalize({{1,12,31},{0,59,59}, localtz}) Timex.datetime({{1,12,31},{0,59,59}}, :local)
iex> use Timex …> Timex.normalize({1,12,31}) Timex.date({1,12,31})
Specs
normalize(:timezone, term) :: Timex.TimezoneInfo.t
normalize(:year | :month | :day | :hour | :minute | :second | :millisecond, integer) :: integer
normalize(:time, {integer, integer, integer} | {integer, integer, integer, integer}) :: Timex.Types.time
normalize(:date, {integer, integer, integer}) :: {Timex.Types.year, Timex.Types.month, Timex.Types.day}
Like normalize/1, but for specific types of values.
Specs
parse(String.t, String.t) ::
{:ok, Timex.DateTime.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
...> expected = Timex.datetime({2016, 2, 29})
...> {:ok, result} = Timex.parse("2016-02-29", "{YYYY}-{0M}-{D}")
...> result == expected
true
iex> use Timex
...> expected = Timex.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.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
Specs
parse(String.t, String.t, atom) ::
{:ok, Timex.DateTime.t} |
{:error, term}
Specs
parse!(String.t, String.t) ::
Timex.DateTime.t |
no_return
Same as parse/2 and parse/3, except parse! raises on error.
See parse/2 or parse/3 docs for usage examples.
Specs
parse!(String.t, String.t, atom) ::
Timex.DateTime.t |
no_return
Return a new Date/DateTime 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.
Example
iex> use Timex
...> expected = Timex.date({2015, 2, 28})
...> result = Timex.set(expected, [month: 2, day: 30])
...> result == expected
true
iex> use Timex
...> expected = Timex.datetime({{2016, 2, 29}, {23, 30, 0}})
...> result = Timex.set(expected, [hour: 30])
...> result === expected
true
Specs
shift(Timex.Date.t | Timex.DateTime.t, [{Timex.Types.shift_units, term}]) ::
Timex.DateTime.t |
{:error, term}
A single function for adjusting the date using various units: timestamp, milliseconds, seconds, minutes, hours, days, weeks, months, years.
TODO: When shifting by timestamps, microseconds are ignored.
The result of applying the shift will either be:
- a Date
- a DateTime
- an AmbiguousDateTime, which will require you to make a choice about which DateTime to use
- an error tuple, which should only occur if something goes wrong with timezone resolution
Examples
Shifting across timezone changes
iex> use Timex
...> %DateTime{} = datetime = Timex.datetime({{2016,3,13}, {1,0,0}}, "America/Chicago")
...> # 2-3 AM doesn't exist
...> shifted = Timex.shift(datetime, hours: 1)
...> {datetime.timezone.abbreviation, shifted.timezone.abbreviation, shifted.hour}
{"CST", "CDT", 3}
Shifting into an ambiguous time period
iex> use Timex
...> %DateTime{} = datetime = Timex.datetime({{1895,12,31}, {0,0,0}}, "Asia/Taipei")
...> %AmbiguousDateTime{} = expected = Timex.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
...> %DateTime{} = datetime = Timex.datetime({2016,2,29})
...> Timex.shift(datetime, years: -1)
Timex.datetime({2015, 3, 1})
Specs
subtract(Timex.Convertable, Timex.Types.timestamp) ::
Timex.DateTime.t |
{:error, term}
Subtract time from a date using a timestamp, i.e. {megasecs, secs, microsecs} Same as shift(date, Time.to_timestamp(5, :minutes) |> Time.invert, :timestamp).
Specs
timezone(Timex.Types.valid_timezone, Timex.Convertable) ::
Timex.TimezoneInfo.t |
Timex.AmbiguousTimezoneInfo.t
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.datetime({2015, 4, 12})
...> tz = Timex.timezone(:utc, date)
...> tz.full_name
"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", "GMT-2"}
Specs
timezones :: [String.t]
Returns a list of all valid timezone names in the Olson database
Specs
to_date(Timex.Convertable) ::
Timex.Date.t |
{:error, term}
Convert a date/time value to a Date struct
Specs
to_datetime(Timex.Convertable) ::
Timex.DateTime.t |
{:error, term}
Convert a date/time value to a DateTime struct
Specs
to_erlang_datetime(Timex.Convertable) ::
Timex.Types.datetime |
{:error, term}
Convert a date/time value to a standard Erlang datetme tuple. i.e. { {year, month, day}, {hour, minute, second} }
Specs
to_gregorian(Timex.Convertable) ::
Timex.Types.gregorian |
{:error, term}
Convert a date/time value to a Gregorian calendar datetme+timezone tuple. i.e. { {year, month, day}, {hour, minute, second}, {offset_hours, timezone_abbreviation}}
Specs
to_gregorian_seconds(Timex.Convertable) ::
non_neg_integer |
{:error, term}
Convert a date/time value to gregorian seconds (seconds since start of year zero)
Specs
to_julian(Timex.Convertable) :: float
Convert a date/time value to a Julian calendar date number
Specs
to_timestamp(Timex.Convertable) ::
Timex.Types.timestamp |
{:error, term}
Convert a date/time value to an Erlang timestamp
Specs
to_unix(Timex.Convertable) ::
non_neg_integer |
{:error, term}
Convert a date/time value to seconds since the UNIX epoch
Specs
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
Specs
validate_format(String.t, atom) ::
:ok |
{:error, term}
Specs
week_of_month(Timex.Convertable) :: Timex.Types.week_of_month
Given a Convertable, this function returns the week number of the date provided, starting at 1.
Examples
iex> Timex.week_of_month({2016,3,5})
1
iex> Timex.week_of_month(Timex.datetime({2016, 3, 14}))
3
Specs
week_of_month(Timex.Types.year, Timex.Types.month, Timex.Types.day) :: Timex.Types.week_of_month
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