TheDates
module provides two types for working with dates:Date
andDateTime
, representing day and millisecond precision, respectively; both are subtypes of the abstractTimeType
. The motivation for distinct types is simple: some operations are much simpler, both in terms of code and mental reasoning, when the complexities of greater precision don't have to be dealt with. For example, since theDate
type only resolves to the precision of a single date (i.e. no hours, minutes, or seconds), normal considerations for time zones, daylight savings/summer time, and leap seconds are unnecessary and avoided.
BothDate
andDateTime
are basically immutableInt64
wrappers. The singleinstant
field of either type is actually aUTInstant{P}
type, which represents a continuously increasing machine timeline based on the UT second[1]. TheDateTime
type is not aware of time zones (naive, in Python parlance), analogous to aLocalDateTime in Java 8. Additional time zone functionality can be added through theTimeZones.jl package, which compiles theIANA time zone database. BothDate
andDateTime
are based on theISO 8601 standard, which follows the proleptic Gregorian calendar. One note is that the ISO 8601 standard is particular about BC/BCE dates. In general, the last day of the BC/BCE era, 1-12-31 BC/BCE, was followed by 1-1-1 AD/CE, thus no year zero exists. The ISO standard, however, states that 1 BC/BCE is year zero, so0000-12-31
is the day before0001-01-01
, and year-0001
(yes, negative one for the year) is 2 BC/BCE, year-0002
is 3 BC/BCE, etc.
Date
andDateTime
types can be constructed by integer orPeriod
types, by parsing, or through adjusters (more on those later):
julia> DateTime(2013)2013-01-01T00:00:00julia> DateTime(2013,7)2013-07-01T00:00:00julia> DateTime(2013,7,1)2013-07-01T00:00:00julia> DateTime(2013,7,1,12)2013-07-01T12:00:00julia> DateTime(2013,7,1,12,30)2013-07-01T12:30:00julia> DateTime(2013,7,1,12,30,59)2013-07-01T12:30:59julia> DateTime(2013,7,1,12,30,59,1)2013-07-01T12:30:59.001julia> Date(2013)2013-01-01julia> Date(2013,7)2013-07-01julia> Date(2013,7,1)2013-07-01julia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1))2013-07-01julia> Date(Dates.Month(7),Dates.Year(2013))2013-07-01
Date
orDateTime
parsing is accomplished by the use of format strings. Format strings work by the notion of definingdelimited orfixed-width "slots" that contain a period to parse and passing the text to parse and format string to aDate
orDateTime
constructor, of the formDate("2015-01-01",dateformat"y-m-d")
orDateTime("20150101",dateformat"yyyymmdd")
.
Delimited slots are marked by specifying the delimiter the parser should expect between two subsequent periods; so"y-m-d"
lets the parser know that between the first and second slots in a date string like"2014-07-16"
, it should find the-
character. They
,m
, andd
characters let the parser know which periods to parse in each slot.
As in the case of constructors above such asDate(2013)
, delimitedDateFormat
s allow for missing parts of dates and times so long as the preceding parts are given. The other parts are given the usual default values. For example,Date("1981-03", dateformat"y-m-d")
returns1981-03-01
, whilstDate("31/12", dateformat"d/m/y")
gives0001-12-31
. (Note that the default year is 1 AD/CE.) An empty string, however, always throws anArgumentError
.
Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. Sodateformat"yyyymmdd"
would correspond to a date string like"20140716"
. The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition"yyyymm"
from one period character to the next.
Support for text-form month parsing is also supported through theu
andU
characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, sou
corresponds to "Jan", "Feb", "Mar", etc. AndU
corresponds to "January", "February", "March", etc. Similar to other name=>value mapping functionsdayname
andmonthname
, custom locales can be loaded by passing in thelocale=>Dict{String,Int}
mapping to theMONTHTOVALUEABBR
andMONTHTOVALUE
dicts for abbreviated and full-name month names, respectively.
The above examples used thedateformat""
string macro. This macro creates aDateFormat
object once when the macro is expanded and uses the sameDateFormat
object even if a code snippet is run multiple times.
julia> for i = 1:10^5 Date("2015-01-01", dateformat"y-m-d") end
Or you can create the DateFormat object explicitly:
julia> df = DateFormat("y-m-d");julia> dt = Date("2015-01-01",df)2015-01-01julia> dt2 = Date("2015-01-02",df)2015-01-02
Alternatively, use broadcasting:
julia> years = ["2015", "2016"];julia> Date.(years, DateFormat("yyyy"))2-element Vector{Date}: 2015-01-01 2016-01-01
For convenience, you may pass the format string directly (e.g.,Date("2015-01-01","y-m-d")
), although this form incurs performance costs if you are parsing the same format repeatedly, as it internally creates a newDateFormat
object each time.
As well as via the constructors, aDate
orDateTime
can be constructed from strings using theparse
andtryparse
functions, but with an optional third argument of typeDateFormat
specifying the format; for example,parse(Date, "06.23.2013", dateformat"m.d.y")
, ortryparse(DateTime, "1999-12-31T23:59:59")
which uses the default format. The notable difference between the functions is that withtryparse
, an error is not thrown if the string is empty or in an invalid format; insteadnothing
is returned.
Before Julia 1.9, empty strings could be passed to constructors andparse
without error, returning as appropriateDateTime(1)
,Date(1)
orTime(0)
. Likewise,tryparse
did not returnnothing
.
A full suite of parsing and formatting tests and examples is available instdlib/Dates/test/io.jl
.
Finding the length of time between twoDate
orDateTime
is straightforward given their underlying representation asUTInstant{Day}
andUTInstant{Millisecond}
, respectively. The difference betweenDate
is returned in the number ofDay
, andDateTime
in the number ofMillisecond
. Similarly, comparingTimeType
is a simple matter of comparing the underlying machine instants (which in turn compares the internalInt64
values).
julia> dt = Date(2012,2,29)2012-02-29julia> dt2 = Date(2000,2,1)2000-02-01julia> dump(dt)Date instant: Dates.UTInstant{Day} periods: Day value: Int64 734562julia> dump(dt2)Date instant: Dates.UTInstant{Day} periods: Day value: Int64 730151julia> dt > dt2truejulia> dt != dt2truejulia> dt + dt2ERROR: MethodError: no method matching +(::Date, ::Date)[...]julia> dt * dt2ERROR: MethodError: no method matching *(::Date, ::Date)[...]julia> dt / dt2ERROR: MethodError: no method matching /(::Date, ::Date)julia> dt - dt24411 daysjulia> dt2 - dt-4411 daysjulia> dt = DateTime(2012,2,29)2012-02-29T00:00:00julia> dt2 = DateTime(2000,2,1)2000-02-01T00:00:00julia> dt - dt2381110400000 milliseconds
Because theDate
andDateTime
types are stored as singleInt64
values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer:
julia> t = Date(2014, 1, 31)2014-01-31julia> Dates.year(t)2014julia> Dates.month(t)1julia> Dates.week(t)5julia> Dates.day(t)31
While propercase return the same value in the correspondingPeriod
type:
julia> Dates.Year(t)2014 yearsjulia> Dates.Day(t)31 days
Compound methods are provided because it is more efficient to access multiple fields at the same time than individually:
julia> Dates.yearmonth(t)(2014, 1)julia> Dates.monthday(t)(1, 31)julia> Dates.yearmonthday(t)(2014, 1, 31)
One may also access the underlyingUTInstant
or integer value:
julia> dump(t)Date instant: Dates.UTInstant{Day} periods: Day value: Int64 735264julia> t.instantDates.UTInstant{Day}(Day(735264))julia> Dates.value(t)735264
Query functions provide calendrical information about aTimeType
. They include information about the day of the week:
julia> t = Date(2014, 1, 31)2014-01-31julia> Dates.dayofweek(t)5julia> Dates.dayname(t)"Friday"julia> Dates.dayofweekofmonth(t) # 5th Friday of January5
Month of the year:
julia> Dates.monthname(t)"January"julia> Dates.daysinmonth(t)31
As well as information about theTimeType
's year and quarter:
julia> Dates.isleapyear(t)falsejulia> Dates.dayofyear(t)31julia> Dates.quarterofyear(t)1julia> Dates.dayofquarter(t)31
Thedayname
andmonthname
methods can also take an optionallocale
keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namelydayabbr
andmonthabbr
. First the mapping is loaded into theLOCALES
variable:
julia> french_months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];julia> french_months_abbrev = ["janv","févr","mars","avril","mai","juin", "juil","août","sept","oct","nov","déc"];julia> french_days = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"];julia> Dates.LOCALES["french"] = Dates.DateLocale(french_months, french_months_abbrev, french_days, [""]);
The above mentioned functions can then be used to perform the queries:
julia> Dates.dayname(t;locale="french")"vendredi"julia> Dates.monthname(t;locale="french")"janvier"julia> Dates.monthabbr(t;locale="french")"janv"
Since the abbreviated versions of the days are not loaded, trying to use the functiondayabbr
will throw an error.
julia> Dates.dayabbr(t;locale="french")ERROR: BoundsError: attempt to access 1-element Vector{String} at index [5]Stacktrace:[...]
It's good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are sometricky issues to deal with (though much less so for day-precision types).
TheDates
module approach tries to follow the simple principle of trying to change as little as possible when doingPeriod
arithmetic. This approach is also often known ascalendrical arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let's take a classic example: add 1 month to January 31st, 2014. What's the answer? Javascript will sayMarch 3 (assumes 31 days). PHP saysMarch 2 (assumes 30 days). The fact is, there is no right answer. In theDates
module, it gives the result of February 28th. How does it figure that out? Consider the classic 7-7-7 gambling game in casinos.
Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date,2014-02-28 + Month(1) == 2014-03-28
. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we're done because that's a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example:
julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1)2014-02-28julia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1)2014-03-01
What's going on there? In the first line, we're adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 monthfirst, where we get 2014-02-29, which adjusts down to 2014-02-28, andthen add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods'types, not their value or positional order; this meansYear
will always be added first, thenMonth
, thenWeek
, etc. Hence the followingdoes result in associativity and Just Works:
julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1)2014-03-01julia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1)2014-03-01
Tricky? Perhaps. What is an innocentDates
user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that's pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the "joys" of dealing with daylight savings, leap seconds, etc.).
As a bonus, all period arithmetic objects work directly with ranges:
julia> dr = Date(2014,1,29):Day(1):Date(2014,2,3)Date("2014-01-29"):Day(1):Date("2014-02-03")julia> collect(dr)6-element Vector{Date}: 2014-01-29 2014-01-30 2014-01-31 2014-02-01 2014-02-02 2014-02-03julia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29)Date("2014-01-29"):Month(1):Date("2014-07-29")julia> collect(dr)7-element Vector{Date}: 2014-01-29 2014-02-28 2014-03-29 2014-04-29 2014-05-29 2014-06-29 2014-07-29
As convenient as date-period arithmetic is, often the kinds of calculations needed on dates take on acalendrical ortemporal nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as "Memorial Day = Last Monday of May", or "Thanksgiving = 4th Thursday of November". These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc.
TheDates
module provides theadjuster API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a singleTimeType
as input and return oradjust to the first or last of the desired period relative to the input.
julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input's week2014-07-14julia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input's month2014-07-31julia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input's quarter2014-09-30
The next two higher-order methods,tonext
, andtoprev
, generalize working with temporal expressions by taking aDateFunction
as first argument, along with a startingTimeType
. ADateFunction
is just a function, usually anonymous, that takes a singleTimeType
as input and returns aBool
,true
indicating a satisfied adjustment criterion. For example:
julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday; # Returns true if the day of the week of x is Tuesdayjulia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday2014-07-15julia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments2014-07-15
This is useful with the do-block syntax for more complex temporal expressions:
julia> Dates.tonext(Date(2014,7,13)) do x # Return true on the 4th Thursday of November (Thanksgiving) Dates.dayofweek(x) == Dates.Thursday && Dates.dayofweekofmonth(x) == 4 && Dates.month(x) == Dates.November end2014-11-27
TheBase.filter
method can be used to obtain all valid dates/moments in a specified range:
# Pittsburgh street cleaning; Every 2nd Tuesday from April to November# Date range from January 1st, 2014 to January 1st, 2015julia> dr = Dates.Date(2014):Day(1):Dates.Date(2015);julia> filter(dr) do x Dates.dayofweek(x) == Dates.Tue && Dates.April <= Dates.month(x) <= Dates.Nov && Dates.dayofweekofmonth(x) == 2 end8-element Vector{Date}: 2014-04-08 2014-05-13 2014-06-10 2014-07-08 2014-08-12 2014-09-09 2014-10-14 2014-11-11
Additional examples and tests are available instdlib/Dates/test/adjusters.jl
.
Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year.Period
types are simpleInt64
wrappers and are constructed by wrapping anyInt64
convertible type, i.e.Year(1)
orMonth(3.0)
. Arithmetic betweenPeriod
of the same type behave like integers, and limitedPeriod-Real
arithmetic is available. You can extract the underlying integer withDates.value
.
julia> y1 = Dates.Year(1)1 yearjulia> y2 = Dates.Year(2)2 yearsjulia> y3 = Dates.Year(10)10 yearsjulia> y1 + y23 yearsjulia> div(y3,y2)5julia> y3 - y28 yearsjulia> y3 % y20 yearsjulia> div(y3,3) # mirrors integer division3 yearsjulia> Dates.value(Dates.Millisecond(10))10
Representing periods or durations that are not integer multiples of the basic types can be achieved with theDates.CompoundPeriod
type. Compound periods may be constructed manually from simplePeriod
types. Additionally, thecanonicalize
function can be used to break down a period into aDates.CompoundPeriod
. This is particularly useful to convert a duration, e.g., a difference of twoDateTime
, into a more convenient representation.
julia> cp = Dates.CompoundPeriod(Day(1),Minute(1))1 day, 1 minutejulia> t1 = DateTime(2018,8,8,16,58,00)2018-08-08T16:58:00julia> t2 = DateTime(2021,6,23,10,00,00)2021-06-23T10:00:00julia> canonicalize(t2-t1) # creates a CompoundPeriod149 weeks, 6 days, 17 hours, 2 minutes
Date
andDateTime
values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) withfloor
,ceil
, orround
:
julia> floor(Date(1985, 8, 16), Dates.Month)1985-08-01julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))2013-02-13T00:45:00julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)2016-08-07T00:00:00
Unlike the numericround
method, which breaks ties toward the even number by default, theTimeType
round
method uses theRoundNearestTiesUp
rounding mode. (It's difficult to guess what breaking ties to nearest "even"TimeType
would entail.) Further details on the availableRoundingMode
s can be found in theAPI reference.
Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious.
In many cases, the resolution specified for rounding (e.g.,Dates.Second(30)
) divides evenly into the next largest period (in this case,Dates.Minute(1)
). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding aDateTime
to the nearest 10 hours?
julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10))2016-07-17T12:00:00
That may seem confusing, given that the hour (12) is not divisible by 10. The reason that2016-07-17T12:00:00
was chosen is that it is 17,676,660 hours after0000-01-01T00:00:00
, and 17,676,660 is divisible by 10.
As JuliaDate
andDateTime
values are represented according to the ISO 8601 standard,0000-01-01T00:00:00
was chosen as base (or "rounding epoch") from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia's internal representation ofDate
s usingRata Die notation; but since the ISO 8601 standard is most visible to the end user,0000-01-01T00:00:00
was chosen as the rounding epoch instead of the0000-12-31T00:00:00
used internally to minimize confusion.)
The only exception to the use of0000-01-01T00:00:00
as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use0000-01-03T00:00:00
(the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks.
Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearestP(2)
, whereP
is aPeriod
type? In some cases (specifically, whenP <: Dates.TimePeriod
) the answer is clear:
julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2))2016-07-17T08:00:00julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2))2016-07-17T08:56:00
This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising:
julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2))2016-07-01T00:00:00
Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0).
This means that rounding aDateTime
to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in aDateTime
with an even value in that field, while rounding aDateTime
to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain.
See theAPI reference for additional information on methods exported from theDates
module.
Dates.Period
—TypePeriodYearQuarterMonthWeekDayHourMinuteSecondMillisecondMicrosecondNanosecond
Period
types represent discrete, human representations of time.
Dates.CompoundPeriod
—TypeCompoundPeriod
ACompoundPeriod
is useful for expressing time periods that are not a fixed multiple of smaller periods. For example, "a year and a day" is not a fixed number of days, but can be expressed using aCompoundPeriod
. In fact, aCompoundPeriod
is automatically generated by addition of different period types, e.g.Year(1) + Day(1)
produces aCompoundPeriod
result.
Dates.Instant
—TypeInstant
Instant
types represent integer-based, machine representations of time as continuous timelines starting from an epoch.
Dates.UTInstant
—TypeUTInstant{T}
TheUTInstant
represents a machine timeline based on UT time (1 day = one revolution of the earth). TheT
is aPeriod
parameter that indicates the resolution or precision of the instant.
Dates.TimeType
—TypeTimeType
TimeType
types wrapInstant
machine instances to provide human representations of the machine instant.Time
,DateTime
andDate
are subtypes ofTimeType
.
Dates.DateTime
—TypeDateTime
DateTime
represents a point in time according to the proleptic Gregorian calendar. The finest resolution of the time is millisecond (i.e., microseconds or nanoseconds cannot be represented by this type). The type supports fixed-point arithmetic, and thus is prone to underflowing (and overflowing). A notable consequence is rounding when adding aMicrosecond
or aNanosecond
:
julia> dt = DateTime(2023, 8, 19, 17, 45, 32, 900)2023-08-19T17:45:32.900julia> dt + Millisecond(1)2023-08-19T17:45:32.901julia> dt + Microsecond(1000) # 1000us == 1ms2023-08-19T17:45:32.901julia> dt + Microsecond(999) # 999us rounded to 1000us2023-08-19T17:45:32.901julia> dt + Microsecond(1499) # 1499 rounded to 1000us2023-08-19T17:45:32.901
Dates.Date
—TypeDate
Date
wraps aUTInstant{Day}
and interprets it according to the proleptic Gregorian calendar.
Dates.Time
—TypeTime
Time
wraps aNanosecond
and represents a specific moment in a 24-hour day.
Dates.TimeZone
—TypeTimeZone
Geographic zone generally based on longitude determining what the time is at a certain location. Some time zones observe daylight savings (eg EST -> EDT). For implementations and more support, see theTimeZones.jl
package
Dates.UTC
—TypeUTC
UTC
, or Coordinated Universal Time, is theTimeZone
from which all others are measured. It is associated with the time at 0° longitude. It is not adjusted for daylight savings.
Dates.DateTime
—MethodDateTime(y, [m, d, h, mi, s, ms]) -> DateTime
Construct aDateTime
type by parts. Arguments must be convertible toInt64
.
Dates.DateTime
—MethodDateTime(periods::Period...) -> DateTime
Construct aDateTime
type byPeriod
type parts. Arguments may be in any order. DateTime parts not provided will default to the value ofDates.default(period)
.
Dates.DateTime
—MethodDateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime
Create aDateTime
through the adjuster API. The starting point will be constructed from the providedy, m, d...
arguments, and will be adjusted untilf::Function
returnstrue
. The step size in adjusting can be provided manually through thestep
keyword.limit
provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case thatf::Function
is never satisfied).
Examples
julia> DateTime(dt -> second(dt) == 40, 2010, 10, 20, 10; step = Second(1))2010-10-20T10:00:40julia> DateTime(dt -> hour(dt) == 20, 2010, 10, 20, 10; step = Hour(1), limit = 5)ERROR: ArgumentError: Adjustment limit reached: 5 iterationsStacktrace:[...]
Dates.DateTime
—MethodDateTime(dt::Date) -> DateTime
Convert aDate
to aDateTime
. The hour, minute, second, and millisecond parts of the newDateTime
are assumed to be zero.
Dates.DateTime
—MethodDateTime(dt::AbstractString, format::AbstractString; locale="english") -> DateTime
Construct aDateTime
by parsing thedt
date time string following the pattern given in theformat
string (seeDateFormat
for syntax).
This method creates aDateFormat
object each time it is called. It is recommended that you create aDateFormat
object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
Examples
julia> DateTime("2020-01-01", "yyyy-mm-dd")2020-01-01T00:00:00julia> a = ("2020-01-01", "2020-01-02");julia> [DateTime(d, dateformat"yyyy-mm-dd") for d ∈ a] # preferred2-element Vector{DateTime}: 2020-01-01T00:00:00 2020-01-02T00:00:00
Dates.format
—Methodformat(dt::TimeType, format::AbstractString; locale="english") -> AbstractString
Construct a string by using aTimeType
object and applying the providedformat
. The following character codes can be used to construct theformat
string:
Code | Examples | Comment |
---|---|---|
y | 6 | Numeric year with a fixed width |
Y | 1996 | Numeric year with a minimum width |
m | 1, 12 | Numeric month with a minimum width |
u | Jan | Month name shortened to 3-chars according to thelocale |
U | January | Full month name according to thelocale keyword |
d | 1, 31 | Day of the month with a minimum width |
H | 0, 23 | Hour (24-hour clock) with a minimum width |
M | 0, 59 | Minute with a minimum width |
S | 0, 59 | Second with a minimum width |
s | 000, 500 | Millisecond with a minimum width of 3 |
e | Mon, Tue | Abbreviated days of the week |
E | Monday | Full day of week name |
The number of sequential code characters indicate the width of the code. A format ofyyyy-mm
specifies that the codey
should have a width of four whilem
a width of two. Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. The fixed-width mode left-pads the value with zeros when it is shorter than the specified width and truncates the value when longer. Minimum-width mode works the same as fixed-width except that it does not truncate values longer than the width.
When creating aformat
you can use any non-code characters as a separator. For example to generate the string "1996-01-15T00:00:00" you could useformat
: "yyyy-mm-ddTHH:MM:SS". Note that if you need to use a code character as a literal you can use the escape character backslash. The string "1996y01m" can be produced with the format "yyyy\ymm\m".
Dates.DateFormat
—TypeDateFormat(format::AbstractString, locale="english") -> DateFormat
Construct a date formatting object that can be used for parsing date strings or formatting a date object as a string. The following character codes can be used to construct theformat
string:
Code | Matches | Comment |
---|---|---|
Y | 1996, 96 | Returns year of 1996, 0096 |
y | 1996, 96 | Same asY onparse but discards excess digits onformat |
m | 1, 01 | Matches 1 or 2-digit months |
u | Jan | Matches abbreviated months according to thelocale keyword |
U | January | Matches full month names according to thelocale keyword |
d | 1, 01 | Matches 1 or 2-digit days |
H | 00 | Matches hours (24-hour clock) |
I | 00 | For outputting hours with 12-hour clock |
M | 00 | Matches minutes |
S | 00 | Matches seconds |
s | .500 | Matches milliseconds |
e | Mon, Tues | Matches abbreviated days of the week |
E | Monday | Matches full name days of the week |
p | AM | Matches AM/PM (case-insensitive) |
yyyymmdd | 19960101 | Matches fixed-width year, month, and day |
Characters not listed above are normally treated as delimiters between date and time slots. For example adt
string of "1996-01-15T00:00:00.0" would have aformat
string like "y-m-dTH:M:S.s". If you need to use a code character as a delimiter you can escape it using backslash. The date "1995y01m" would have the format "y\ym\m".
Note that 12:00AM corresponds 00:00 (midnight), and 12:00PM corresponds to 12:00 (noon). When parsing a time with ap
specifier, any hour (eitherH
orI
) is interpreted as as a 12-hour clock, so theI
code is mainly useful for output.
Creating a DateFormat object is expensive. Whenever possible, create it once and use it many times or try thedateformat""
string macro. Using this macro creates the DateFormat object once at macro expansion time and reuses it later. There are also severalpre-defined formatters, listed later.
SeeDateTime
andformat
for how to use a DateFormat object to parse and write Date strings respectively.
Dates.@dateformat_str
—Macrodateformat"Y-m-d H:M:S"
Create aDateFormat
object. Similar toDateFormat("Y-m-d H:M:S")
but creates the DateFormat object once during macro expansion.
SeeDateFormat
for details about format specifiers.
Dates.DateTime
—MethodDateTime(dt::AbstractString, df::DateFormat=ISODateTimeFormat) -> DateTime
Construct aDateTime
by parsing thedt
date time string following the pattern given in theDateFormat
object, or dateformat"yyyy-mm-dd\THH:MM:SS.s" if omitted.
Similar toDateTime(::AbstractString, ::AbstractString)
but more efficient when repeatedly parsing similarly formatted date time strings with a pre-createdDateFormat
object.
Dates.Date
—MethodDate(y, [m, d]) -> Date
Construct aDate
type by parts. Arguments must be convertible toInt64
.
Dates.Date
—MethodDate(period::Period...) -> Date
Construct aDate
type byPeriod
type parts. Arguments may be in any order.Date
parts not provided will default to the value ofDates.default(period)
.
Dates.Date
—MethodDate(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date
Create aDate
through the adjuster API. The starting point will be constructed from the providedy, m, d
arguments, and will be adjusted untilf::Function
returnstrue
. The step size in adjusting can be provided manually through thestep
keyword.limit
provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given thatf::Function
is never satisfied).
Examples
julia> Date(date -> week(date) == 20, 2010, 01, 01)2010-05-17julia> Date(date -> year(date) == 2010, 2000, 01, 01)2010-01-01julia> Date(date -> month(date) == 10, 2000, 01, 01; limit = 5)ERROR: ArgumentError: Adjustment limit reached: 5 iterationsStacktrace:[...]
Dates.Date
—MethodDate(dt::DateTime) -> Date
Convert aDateTime
to aDate
. The hour, minute, second, and millisecond parts of theDateTime
are truncated, so only the year, month and day parts are used in construction.
Dates.Date
—MethodDate(d::AbstractString, format::AbstractString; locale="english") -> Date
Construct aDate
by parsing thed
date string following the pattern given in theformat
string (seeDateFormat
for syntax).
This method creates aDateFormat
object each time it is called. It is recommended that you create aDateFormat
object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
Examples
julia> Date("2020-01-01", "yyyy-mm-dd")2020-01-01julia> a = ("2020-01-01", "2020-01-02");julia> [Date(d, dateformat"yyyy-mm-dd") for d ∈ a] # preferred2-element Vector{Date}: 2020-01-01 2020-01-02
Dates.Date
—MethodDate(d::AbstractString, df::DateFormat=ISODateFormat) -> Date
Construct aDate
by parsing thed
date string following the pattern given in theDateFormat
object, or dateformat"yyyy-mm-dd" if omitted.
Similar toDate(::AbstractString, ::AbstractString)
but more efficient when repeatedly parsing similarly formatted date strings with a pre-createdDateFormat
object.
Dates.Time
—MethodTime(h, [mi, s, ms, us, ns]) -> Time
Construct aTime
type by parts. Arguments must be convertible toInt64
.
Dates.Time
—MethodTime(period::TimePeriod...) -> Time
Construct aTime
type byPeriod
type parts. Arguments may be in any order.Time
parts not provided will default to the value ofDates.default(period)
.
Dates.Time
—MethodTime(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000)Time(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000)Time(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000)Time(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000)
Create aTime
through the adjuster API. The starting point will be constructed from the providedh, mi, s, ms, us
arguments, and will be adjusted untilf::Function
returnstrue
. The step size in adjusting can be provided manually through thestep
keyword.limit
provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case thatf::Function
is never satisfied). Note that the default step will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second arguments are provided, the default step will beMillisecond(1)
instead ofSecond(1)
.
Examples
julia> Time(t -> minute(t) == 30, 20)20:30:00julia> Time(t -> minute(t) == 0, 20)20:00:00julia> Time(t -> hour(t) == 10, 3; limit = 5)ERROR: ArgumentError: Adjustment limit reached: 5 iterationsStacktrace:[...]
Dates.Time
—MethodTime(dt::DateTime) -> Time
Convert aDateTime
to aTime
. The hour, minute, second, and millisecond parts of theDateTime
are used to create the newTime
. Microsecond and nanoseconds are zero by default.
Dates.Time
—MethodTime(t::AbstractString, format::AbstractString; locale="english") -> Time
Construct aTime
by parsing thet
time string following the pattern given in theformat
string (seeDateFormat
for syntax).
This method creates aDateFormat
object each time it is called. It is recommended that you create aDateFormat
object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
Examples
julia> Time("12:34pm", "HH:MMp")12:34:00julia> a = ("12:34pm", "2:34am");julia> [Time(d, dateformat"HH:MMp") for d ∈ a] # preferred2-element Vector{Time}: 12:34:00 02:34:00
Dates.Time
—MethodTime(t::AbstractString, df::DateFormat=ISOTimeFormat) -> Time
Construct aTime
by parsing thet
date time string following the pattern given in theDateFormat
object, or dateformat"HH:MM:SS.s" if omitted.
Similar toTime(::AbstractString, ::AbstractString)
but more efficient when repeatedly parsing similarly formatted time strings with a pre-createdDateFormat
object.
Dates.now
—Methodnow() -> DateTime
Return aDateTime
corresponding to the user's system time including the system timezone locale.
Dates.now
—Methodnow(::Type{UTC}) -> DateTime
Return aDateTime
corresponding to the user's system time as UTC/GMT. For other time zones, see the TimeZones.jl package.
Examples
julia> now(UTC)2023-01-04T10:52:24.864
Base.eps
—Methodeps(::Type{DateTime}) -> Millisecondeps(::Type{Date}) -> Dayeps(::Type{Time}) -> Nanosecondeps(::TimeType) -> Period
Return the smallest unit value supported by theTimeType
.
Examples
julia> eps(DateTime)1 millisecondjulia> eps(Date)1 dayjulia> eps(Time)1 nanosecond
Dates.year
—Functionyear(dt::TimeType) -> Int64
The year of aDate
orDateTime
as anInt64
.
Dates.month
—Functionmonth(dt::TimeType) -> Int64
The month of aDate
orDateTime
as anInt64
.
Dates.week
—Functionweek(dt::TimeType) -> Int64
Return theISO week date of aDate
orDateTime
as anInt64
. Note that the first week of a year is the week that contains the first Thursday of the year, which can result in dates prior to January 4th being in the last week of the previous year. For example,week(Date(2005, 1, 1))
is the 53rd week of 2004.
Examples
julia> week(Date(1989, 6, 22))25julia> week(Date(2005, 1, 1))53julia> week(Date(2004, 12, 31))53
Dates.day
—Functionday(dt::TimeType) -> Int64
The day of month of aDate
orDateTime
as anInt64
.
Dates.hour
—Functionhour(dt::DateTime) -> Int64
The hour of day of aDateTime
as anInt64
.
hour(t::Time) -> Int64
The hour of aTime
as anInt64
.
Dates.minute
—Functionminute(dt::DateTime) -> Int64
The minute of aDateTime
as anInt64
.
minute(t::Time) -> Int64
The minute of aTime
as anInt64
.
Dates.second
—Functionsecond(dt::DateTime) -> Int64
The second of aDateTime
as anInt64
.
second(t::Time) -> Int64
The second of aTime
as anInt64
.
Dates.millisecond
—Functionmillisecond(dt::DateTime) -> Int64
The millisecond of aDateTime
as anInt64
.
millisecond(t::Time) -> Int64
The millisecond of aTime
as anInt64
.
Dates.microsecond
—Functionmicrosecond(t::Time) -> Int64
The microsecond of aTime
as anInt64
.
Dates.nanosecond
—Functionnanosecond(t::Time) -> Int64
The nanosecond of aTime
as anInt64
.
Dates.Year
—MethodYear(v)
Construct aYear
object with the givenv
value. Input must be losslessly convertible to anInt64
.
Dates.Month
—MethodMonth(v)
Construct aMonth
object with the givenv
value. Input must be losslessly convertible to anInt64
.
Dates.Week
—MethodWeek(v)
Construct aWeek
object with the givenv
value. Input must be losslessly convertible to anInt64
.
Dates.Day
—MethodDay(v)
Construct aDay
object with the givenv
value. Input must be losslessly convertible to anInt64
.
Dates.Hour
—MethodHour(dt::DateTime) -> Hour
The hour part of a DateTime as aHour
.
Dates.Minute
—MethodMinute(dt::DateTime) -> Minute
The minute part of a DateTime as aMinute
.
Dates.Second
—MethodSecond(dt::DateTime) -> Second
The second part of a DateTime as aSecond
.
Dates.Millisecond
—MethodMillisecond(dt::DateTime) -> Millisecond
The millisecond part of a DateTime as aMillisecond
.
Dates.Microsecond
—MethodMicrosecond(dt::Time) -> Microsecond
The microsecond part of a Time as aMicrosecond
.
Dates.Nanosecond
—MethodNanosecond(dt::Time) -> Nanosecond
The nanosecond part of a Time as aNanosecond
.
Dates.yearmonth
—Functionyearmonth(dt::TimeType) -> (Int64, Int64)
Simultaneously return the year and month parts of aDate
orDateTime
.
Dates.monthday
—Functionmonthday(dt::TimeType) -> (Int64, Int64)
Simultaneously return the month and day parts of aDate
orDateTime
.
Dates.yearmonthday
—Functionyearmonthday(dt::TimeType) -> (Int64, Int64, Int64)
Simultaneously return the year, month and day parts of aDate
orDateTime
.
Dates.dayname
—Functiondayname(dt::TimeType; locale="english") -> Stringdayname(day::Integer; locale="english") -> String
Return the full day name corresponding to the day of the week of theDate
orDateTime
in the givenlocale
. Also acceptsInteger
.
Examples
julia> dayname(Date("2000-01-01"))"Saturday"julia> dayname(4)"Thursday"
Dates.dayabbr
—Functiondayabbr(dt::TimeType; locale="english") -> Stringdayabbr(day::Integer; locale="english") -> String
Return the abbreviated name corresponding to the day of the week of theDate
orDateTime
in the givenlocale
. Also acceptsInteger
.
Examples
julia> dayabbr(Date("2000-01-01"))"Sat"julia> dayabbr(3)"Wed"
Dates.dayofweek
—Functiondayofweek(dt::TimeType) -> Int64
Return the day of the week as anInt64
with1 = Monday, 2 = Tuesday, etc.
.
Examples
julia> dayofweek(Date("2000-01-01"))6
Dates.dayofmonth
—Functiondayofmonth(dt::TimeType) -> Int64
The day of month of aDate
orDateTime
as anInt64
.
Dates.dayofweekofmonth
—Functiondayofweekofmonth(dt::TimeType) -> Int
For the day of week ofdt
, return which number it is indt
's month. So if the day of the week ofdt
is Monday, then1 = First Monday of the month, 2 = Second Monday of the month, etc.
In the range 1:5.
Examples
julia> dayofweekofmonth(Date("2000-02-01"))1julia> dayofweekofmonth(Date("2000-02-08"))2julia> dayofweekofmonth(Date("2000-02-15"))3
Dates.daysofweekinmonth
—Functiondaysofweekinmonth(dt::TimeType) -> Int
For the day of week ofdt
, return the total number of that day of the week indt
's month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by includingdayofweekofmonth(dt) == daysofweekinmonth(dt)
in the adjuster function.
Examples
julia> daysofweekinmonth(Date("2005-01-01"))5julia> daysofweekinmonth(Date("2005-01-04"))4
Dates.monthname
—Functionmonthname(dt::TimeType; locale="english") -> Stringmonthname(month::Integer, locale="english") -> String
Return the full name of the month of theDate
orDateTime
orInteger
in the givenlocale
.
Examples
julia> monthname(Date("2005-01-04"))"January"julia> monthname(2)"February"
Dates.monthabbr
—Functionmonthabbr(dt::TimeType; locale="english") -> Stringmonthabbr(month::Integer, locale="english") -> String
Return the abbreviated month name of theDate
orDateTime
orInteger
in the givenlocale
.
Examples
julia> monthabbr(Date("2005-01-04"))"Jan"julia> monthabbr(2)"Feb"
Dates.daysinmonth
—Functiondaysinmonth(dt::TimeType) -> Int
Return the number of days in the month ofdt
. Value will be 28, 29, 30, or 31.
Examples
julia> daysinmonth(Date("2000-01"))31julia> daysinmonth(Date("2001-02"))28julia> daysinmonth(Date("2000-02"))29
Dates.isleapyear
—Functionisleapyear(dt::TimeType) -> Bool
Returntrue
if the year ofdt
is a leap year.
Examples
julia> isleapyear(Date("2004"))truejulia> isleapyear(Date("2005"))false
Dates.dayofyear
—Functiondayofyear(dt::TimeType) -> Int
Return the day of the year fordt
with January 1st being day 1.
Dates.daysinyear
—Functiondaysinyear(dt::TimeType) -> Int
Return 366 if the year ofdt
is a leap year, otherwise return 365.
Examples
julia> daysinyear(1999)365julia> daysinyear(2000)366
Dates.quarterofyear
—Functionquarterofyear(dt::TimeType) -> Int
Return the quarter thatdt
resides in. Range of value is 1:4.
Dates.dayofquarter
—Functiondayofquarter(dt::TimeType) -> Int
Return the day of the current quarter ofdt
. Range of value is 1:92.
Base.trunc
—Methodtrunc(dt::TimeType, ::Type{Period}) -> TimeType
Truncates the value ofdt
according to the providedPeriod
type.
Examples
julia> trunc(DateTime("1996-01-01T12:30:00"), Day)1996-01-01T00:00:00
Dates.firstdayofweek
—Functionfirstdayofweek(dt::TimeType) -> TimeType
Adjustsdt
to the Monday of its week.
Examples
julia> firstdayofweek(DateTime("1996-01-05T12:30:00"))1996-01-01T00:00:00
Dates.lastdayofweek
—Functionlastdayofweek(dt::TimeType) -> TimeType
Adjustsdt
to the Sunday of its week.
Examples
julia> lastdayofweek(DateTime("1996-01-05T12:30:00"))1996-01-07T00:00:00
Dates.firstdayofmonth
—Functionfirstdayofmonth(dt::TimeType) -> TimeType
Adjustsdt
to the first day of its month.
Examples
julia> firstdayofmonth(DateTime("1996-05-20"))1996-05-01T00:00:00
Dates.lastdayofmonth
—Functionlastdayofmonth(dt::TimeType) -> TimeType
Adjustsdt
to the last day of its month.
Examples
julia> lastdayofmonth(DateTime("1996-05-20"))1996-05-31T00:00:00
Dates.firstdayofyear
—Functionfirstdayofyear(dt::TimeType) -> TimeType
Adjustsdt
to the first day of its year.
Examples
julia> firstdayofyear(DateTime("1996-05-20"))1996-01-01T00:00:00
Dates.lastdayofyear
—Functionlastdayofyear(dt::TimeType) -> TimeType
Adjustsdt
to the last day of its year.
Examples
julia> lastdayofyear(DateTime("1996-05-20"))1996-12-31T00:00:00
Dates.firstdayofquarter
—Functionfirstdayofquarter(dt::TimeType) -> TimeType
Adjustsdt
to the first day of its quarter.
Examples
julia> firstdayofquarter(DateTime("1996-05-20"))1996-04-01T00:00:00julia> firstdayofquarter(DateTime("1996-08-20"))1996-07-01T00:00:00
Dates.lastdayofquarter
—Functionlastdayofquarter(dt::TimeType) -> TimeType
Adjustsdt
to the last day of its quarter.
Examples
julia> lastdayofquarter(DateTime("1996-05-20"))1996-06-30T00:00:00julia> lastdayofquarter(DateTime("1996-08-20"))1996-09-30T00:00:00
Dates.tonext
—Methodtonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType
Adjustsdt
to the next day of week corresponding todow
with1 = Monday, 2 = Tuesday, etc
. Settingsame=true
allows the currentdt
to be considered as the nextdow
, allowing for no adjustment to occur.
Dates.toprev
—Methodtoprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType
Adjustsdt
to the previous day of week corresponding todow
with1 = Monday, 2 = Tuesday, etc
. Settingsame=true
allows the currentdt
to be considered as the previousdow
, allowing for no adjustment to occur.
Dates.tofirst
—Functiontofirst(dt::TimeType, dow::Int; of=Month) -> TimeType
Adjustsdt
to the firstdow
of its month. Alternatively,of=Year
will adjust to the firstdow
of the year.
Dates.tolast
—Functiontolast(dt::TimeType, dow::Int; of=Month) -> TimeType
Adjustsdt
to the lastdow
of its month. Alternatively,of=Year
will adjust to the lastdow
of the year.
Dates.tonext
—Methodtonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType
Adjustsdt
by iterating at mostlimit
iterations bystep
increments untilfunc
returnstrue
.func
must take a singleTimeType
argument and return aBool
.same
allowsdt
to be considered in satisfyingfunc
.
Dates.toprev
—Methodtoprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType
Adjustsdt
by iterating at mostlimit
iterations bystep
increments untilfunc
returnstrue
.func
must take a singleTimeType
argument and return aBool
.same
allowsdt
to be considered in satisfyingfunc
.
Dates.Period
—MethodYear(v)Quarter(v)Month(v)Week(v)Day(v)Hour(v)Minute(v)Second(v)Millisecond(v)Microsecond(v)Nanosecond(v)
Construct aPeriod
type with the givenv
value. Input must be losslessly convertible to anInt64
.
Dates.CompoundPeriod
—MethodCompoundPeriod(periods) -> CompoundPeriod
Construct aCompoundPeriod
from aVector
ofPeriod
s. AllPeriod
s of the same type will be added together.
Examples
julia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))25 hoursjulia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))-1 hour, 1 minutejulia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))1 month, -2 weeksjulia> Dates.CompoundPeriod(Dates.Minute(50000))50000 minutes
Dates.canonicalize
—Functioncanonicalize(::CompoundPeriod) -> CompoundPeriod
Reduces theCompoundPeriod
into its canonical form by applying the following rules:
Period
large enough be partially representable by a coarserPeriod
will be broken into multiplePeriod
s (eg.Hour(30)
becomesDay(1) + Hour(6)
)Period
s with opposite signs will be combined when possible (eg.Hour(1) - Day(1)
becomes-Hour(23)
)Examples
julia> canonicalize(Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13)))1 day, 1 hourjulia> canonicalize(Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1)))-59 minutesjulia> canonicalize(Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2)))1 month, -2 weeksjulia> canonicalize(Dates.CompoundPeriod(Dates.Minute(50000)))4 weeks, 6 days, 17 hours, 20 minutes
Dates.value
—FunctionDates.value(x::Period) -> Int64
For a given period, return the value associated with that period. For example,value(Millisecond(10))
returns 10 as an integer.
Dates.default
—Functiondefault(p::Period) -> Period
Return a sensible "default" value for the input Period by returningT(1)
for Year, Month, and Day, andT(0)
for Hour, Minute, Second, and Millisecond.
Dates.periods
—FunctionDates.periods(::CompoundPeriod) -> Vector{Period}
Return theVector
ofPeriod
s that comprise the givenCompoundPeriod
.
This function requires Julia 1.7 or later.
Date
andDateTime
values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) withfloor
,ceil
, orround
.
Base.floor
—Methodfloor(dt::TimeType, p::Period) -> TimeType
Return the nearestDate
orDateTime
less than or equal todt
at resolutionp
.
For convenience,p
may be a type instead of a value:floor(dt, Dates.Hour)
is a shortcut forfloor(dt, Dates.Hour(1))
.
julia> floor(Date(1985, 8, 16), Month)1985-08-01julia> floor(DateTime(2013, 2, 13, 0, 31, 20), Minute(15))2013-02-13T00:30:00julia> floor(DateTime(2016, 8, 6, 12, 0, 0), Day)2016-08-06T00:00:00
Base.ceil
—Methodceil(dt::TimeType, p::Period) -> TimeType
Return the nearestDate
orDateTime
greater than or equal todt
at resolutionp
.
For convenience,p
may be a type instead of a value:ceil(dt, Dates.Hour)
is a shortcut forceil(dt, Dates.Hour(1))
.
julia> ceil(Date(1985, 8, 16), Month)1985-09-01julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Minute(15))2013-02-13T00:45:00julia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Day)2016-08-07T00:00:00
Base.round
—Methodround(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType
Return theDate
orDateTime
nearest todt
at resolutionp
. By default (RoundNearestTiesUp
), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.
For convenience,p
may be a type instead of a value:round(dt, Dates.Hour)
is a shortcut forround(dt, Dates.Hour(1))
.
julia> round(Date(1985, 8, 16), Month)1985-08-01julia> round(DateTime(2013, 2, 13, 0, 31, 20), Minute(15))2013-02-13T00:30:00julia> round(DateTime(2016, 8, 6, 12, 0, 0), Day)2016-08-07T00:00:00
Valid rounding modes forround(::TimeType, ::Period, ::RoundingMode)
areRoundNearestTiesUp
(default),RoundDown
(floor
), andRoundUp
(ceil
).
MostPeriod
values can also be rounded to a specified resolution:
Base.floor
—Methodfloor(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
Roundx
down to the nearest multiple ofprecision
. Ifx
andprecision
are different subtypes ofPeriod
, the return value will have the same type asprecision
.
For convenience,precision
may be a type instead of a value:floor(x, Dates.Hour)
is a shortcut forfloor(x, Dates.Hour(1))
.
julia> floor(Day(16), Week)2 weeksjulia> floor(Minute(44), Minute(15))30 minutesjulia> floor(Hour(36), Day)1 day
Rounding to aprecision
ofMonth
s orYear
s is not supported, as thesePeriod
s are of inconsistent length.
Base.ceil
—Methodceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
Roundx
up to the nearest multiple ofprecision
. Ifx
andprecision
are different subtypes ofPeriod
, the return value will have the same type asprecision
.
For convenience,precision
may be a type instead of a value:ceil(x, Dates.Hour)
is a shortcut forceil(x, Dates.Hour(1))
.
julia> ceil(Day(16), Week)3 weeksjulia> ceil(Minute(44), Minute(15))45 minutesjulia> ceil(Hour(36), Day)2 days
Rounding to aprecision
ofMonth
s orYear
s is not supported, as thesePeriod
s are of inconsistent length.
Base.round
—Methodround(x::Period, precision::T, [r::RoundingMode]) where T <: Union{TimePeriod, Week, Day} -> T
Roundx
to the nearest multiple ofprecision
. Ifx
andprecision
are different subtypes ofPeriod
, the return value will have the same type asprecision
. By default (RoundNearestTiesUp
), ties (e.g., rounding 90 minutes to the nearest hour) will be rounded up.
For convenience,precision
may be a type instead of a value:round(x, Dates.Hour)
is a shortcut forround(x, Dates.Hour(1))
.
julia> round(Day(16), Week)2 weeksjulia> round(Minute(44), Minute(15))45 minutesjulia> round(Hour(36), Day)2 days
Valid rounding modes forround(::Period, ::T, ::RoundingMode)
areRoundNearestTiesUp
(default),RoundDown
(floor
), andRoundUp
(ceil
).
Rounding to aprecision
ofMonth
s orYear
s is not supported, as thesePeriod
s are of inconsistent length.
The following functions are not exported:
Dates.floorceil
—Functionfloorceil(dt::TimeType, p::Period) -> (TimeType, TimeType)
Simultaneously return thefloor
andceil
of aDate
orDateTime
at resolutionp
. More efficient than calling bothfloor
andceil
individually.
floorceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> (T, T)
Simultaneously return thefloor
andceil
ofPeriod
at resolutionp
. More efficient than calling bothfloor
andceil
individually.
Dates.epochdays2date
—Functionepochdays2date(days) -> Date
Take the number of days since the rounding epoch (0000-01-01T00:00:00
) and return the correspondingDate
.
Dates.epochms2datetime
—Functionepochms2datetime(milliseconds) -> DateTime
Take the number of milliseconds since the rounding epoch (0000-01-01T00:00:00
) and return the correspondingDateTime
.
Dates.date2epochdays
—Functiondate2epochdays(dt::Date) -> Int64
Take the givenDate
and return the number of days since the rounding epoch (0000-01-01T00:00:00
) as anInt64
.
Dates.datetime2epochms
—Functiondatetime2epochms(dt::DateTime) -> Int64
Take the givenDateTime
and return the number of milliseconds since the rounding epoch (0000-01-01T00:00:00
) as anInt64
.
Dates.today
—Functiontoday() -> Date
Return the date portion ofnow()
.
Dates.unix2datetime
—Functionunix2datetime(x) -> DateTime
Take the number of seconds since unix epoch1970-01-01T00:00:00
and convert to the correspondingDateTime
.
Dates.datetime2unix
—Functiondatetime2unix(dt::DateTime) -> Float64
Take the givenDateTime
and return the number of seconds since the unix epoch1970-01-01T00:00:00
as aFloat64
.
Dates.julian2datetime
—Functionjulian2datetime(julian_days) -> DateTime
Take the number of Julian calendar days since epoch-4713-11-24T12:00:00
and return the correspondingDateTime
.
Dates.datetime2julian
—Functiondatetime2julian(dt::DateTime) -> Float64
Take the givenDateTime
and return the number of Julian calendar days since the julian epoch-4713-11-24T12:00:00
as aFloat64
.
Dates.rata2datetime
—Functionrata2datetime(days) -> DateTime
Take the number of Rata Die days since epoch0000-12-31T00:00:00
and return the correspondingDateTime
.
Dates.datetime2rata
—Functiondatetime2rata(dt::TimeType) -> Int64
Return the number of Rata Die days since epoch from the givenDate
orDateTime
.
Days of the Week:
Variable | Abbr. | Value (Int) |
---|---|---|
Monday | Mon | 1 |
Tuesday | Tue | 2 |
Wednesday | Wed | 3 |
Thursday | Thu | 4 |
Friday | Fri | 5 |
Saturday | Sat | 6 |
Sunday | Sun | 7 |
Months of the Year:
Variable | Abbr. | Value (Int) |
---|---|---|
January | Jan | 1 |
February | Feb | 2 |
March | Mar | 3 |
April | Apr | 4 |
May | May | 5 |
June | Jun | 6 |
July | Jul | 7 |
August | Aug | 8 |
September | Sep | 9 |
October | Oct | 10 |
November | Nov | 11 |
December | Dec | 12 |
Dates.ISODateTimeFormat
—ConstantDates.ISODateTimeFormat
Describes the ISO8601 formatting for a date and time. This is the default value forDates.format
of aDateTime
.
Examples
julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), ISODateTimeFormat)"2018-08-08T12:00:43.001"
Dates.ISODateFormat
—ConstantDates.ISODateFormat
Describes the ISO8601 formatting for a date. This is the default value forDates.format
of aDate
.
Examples
julia> Dates.format(Date(2018, 8, 8), ISODateFormat)"2018-08-08"
Dates.ISOTimeFormat
—ConstantDates.ISOTimeFormat
Describes the ISO8601 formatting for a time. This is the default value forDates.format
of aTime
.
Examples
julia> Dates.format(Time(12, 0, 43, 1), ISOTimeFormat)"12:00:43.001"
Dates.RFC1123Format
—ConstantDates.RFC1123Format
Describes the RFC1123 formatting for a date and time.
Examples
julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), RFC1123Format)"Wed, 08 Aug 2018 12:00:43"
Date
andDateTime
are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally calledUT or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates.Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.