Conceptcore
Date and time values
Also called date and time types, date-time, datetime, instant, timestamp, local date, civil time, duration, period, naive and aware datetimes.
A program keeps time in different values: an instant on the global time-line, a local date and time as people read it, and amounts of time as exact durations or calendar periods.
- Applies to
- core-languages
Idea
A program meets time in two forms. The first form is a point on the global time-line, such as the moment when a payment went through or a log line was written. The second form is what people read on a calendar and a clock, such as 9 March 2024, 12:00. The two forms are not the same, because one moment has different calendar readings in different places. Python names the split with the words aware and naive: "An aware object represents a specific moment in time that is not open to interpretation."1 But "A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects."1
Amounts of time also have two forms. A duration, such as 90 minutes, is an exact number of seconds. A period, such as 1 month, is a number of calendar units, and its length in seconds depends on the date where it starts.
from datetime import date, datetime, timedelta, timezone
# An instant: a moment on the time-line, written here in UTC.
paid = datetime(2024, 3, 9, 12, 0, tzinfo=timezone.utc)
# The same instant on a clock in a zone that is 9 hours ahead of UTC.
print(paid.astimezone(timezone(timedelta(hours=9))))
# A local date and time: a calendar and clock reading with no zone.
meeting = datetime(2024, 3, 9, 12, 0)
print(meeting, meeting.tzinfo)
# A date with no time, and an exact duration.
print(date(2024, 3, 9), timedelta(minutes=90))
# The usual number for an instant: seconds since 1970-01-01 00:00 UTC.
print(int(paid.timestamp()))
2024-03-09 21:00:00+09:00
2024-03-09 12:00:00 None
2024-03-09 1:30:00
1709985600
The value paid is one moment, and the program can show it on any clock. The value meeting has no zone, so it is not a moment until the program adds a zone. Most bugs with dates come from a mix of these kinds of values.
How it works
An instant is a count from an epoch. Most systems keep an instant as a number of units after a fixed moment. In C++, "A clock consists of a starting point (or epoch) and a tick rate."2 and "A time point is a duration of time that has passed since the epoch of a specific clock."2 POSIX defines Seconds Since the Epoch as "A value that approximates the number of seconds that have elapsed since the Epoch."3 JavaScript Date objects "encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC"4. In Java, "Instant is essentially a numeric timestamp."5 In Go, "A Time represents an instant in time with nanosecond precision."6 The unit is different in each system: seconds in POSIX, milliseconds in JavaScript and nanoseconds in Go. See Unix time.
A local date and time is a set of fields. The fields are the year, month, day, hour, minute and second. In Java, "LocalDate stores a date without a time."5 Python describes its date type as "An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect."1 Most libraries use this proleptic Gregorian calendar. Fields are good for display and for calendar steps, such as the same day in the next month.
A zone joins the two forms. To turn a local date and time into an instant, a program needs the offset from UTC at that date and place. A value with an offset names one instant. In .NET, "The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC."7 A time zone such as America/New_York has rules that change its offset during the year. Thus a local time can be missing on the day when the clocks move forward, and it can occur two times on the day when they move back. See Time zone and IANA time zone database.
Durations and periods. Java has a type for each: "A Duration is a simple measure of time along the time-line in nanoseconds. A Period expresses an amount of time in units meaningful to humans, such as years or days."5 In New York, 2024-03-09 12:00 plus a period of 1 day is 2024-03-10 12:00, but plus a duration of 24 hours is 13:00, because the clocks moved forward in that night. The Java example shows this. See Calendar arithmetic.
Two clocks. A computer has a wall clock, which the system can set back or forward, and a monotonic clock, which only moves forward. Go states the rule: "The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time."6 Rust has a type for each clock. Instant is "A measurement of a monotonically nondecreasing clock."8 SystemTime is "A measurement of the system clock, useful for talking to external entities like the file system or other processes."9 See Measure elapsed time.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Standard library | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript uses the JavaScript Date and Temporal objects, with types from the lib settings. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | On the JVM, Kotlin uses java.time with Instant, LocalDate, ZonedDateTime, Duration and Period. kotlin.time.Duration is in the standard library, and the library kotlinx-datetime gives the same types on all platforms. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL has the types DATE, TIME, TIMESTAMP, TIMESTAMP WITH TIME ZONE and INTERVAL. The functions and the time zone support differ between database systems. |
| Bash | Idiom | Bash has no date type. The variable EPOCHSECONDS gives the Unix time, the printf format %(datefmt)T formats it, and the external command date converts and formats dates. No example file exists. |
| PowerShell | Standard library | PowerShell uses the .NET types DateTime, DateTimeOffset and TimeSpan. Get-Date gives the current date and time, and New-TimeSpan makes a duration. No example file exists because pwsh is not installed. |
| HTML | Idiom | The time element marks a date or time, and its datetime attribute holds a machine-readable form such as 2024-03-09T12:00Z. The input types date, time and datetime-local let a user pick a value. |
| CSS | Does not apply | CSS has no dates. Its time type, such as 200ms or 1s, is a duration for transitions and animations. |
| Regular expressions | Does not apply | A regular expression has no time values. A pattern can check only the form of a date string, not whether the date exists. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | datetime (aware or naive), date, time and timedelta; zoneinfo for zones |
| JavaScript | native | Date, an instant in milliseconds with a mutable API; Temporal with Instant, PlainDate, ZonedDateTime and Duration |
| TypeScript | native | the JavaScript Date and Temporal |
| Java | stdlib | java.time: Instant, LocalDate, LocalDateTime, ZonedDateTime, Duration and Period; the old java.util.Date |
| Kotlin | stdlib | java.time on the JVM; kotlin.time.Duration; the library kotlinx-datetime |
| C# | stdlib | DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan and TimeZoneInfo |
| Go | stdlib | time.Time, an instant with a location and a monotonic reading; time.Duration |
| Rust | stdlib | SystemTime, Instant and Duration, with no calendar types; the crates chrono, time and jiff |
| C | stdlib | time_t, struct tm and struct timespec; gmtime, mktime and strftime |
| C++ | stdlib | std::chrono clocks, time_point and duration; year_month_day and zoned_time |
| Bash | idiom | the variable EPOCHSECONDS and the format %(datefmt)T of printf; the external command date |
| PowerShell | stdlib | the .NET types; the cmdlets Get-Date and New-TimeSpan |
| SQL | native | the types DATE, TIME, TIMESTAMP, TIMESTAMP WITH TIME ZONE and INTERVAL |
| Regex | n/a | no time values; a pattern can check only the form of a date string |
| HTML | idiom | the time element with a machine-readable datetime attribute; date inputs |
| CSS | n/a | no dates; the time type, such as 200ms, is a duration for animations |
JavaScript has two APIs. The old one is Date: "With the introduction of the Temporal API, the Date object is considered a legacy feature."4 The Temporal object "is designed as a full replacement for the Date object."10 It has separate types for an instant, a zoned date and time, a plain date and a duration, as Java has.
Java made the same change earlier. The package java.time has a type for each kind of value, and "All the classes are immutable and thread-safe."5 .NET added DateTimeOffset to DateTime, and "The DateTimeOffset type includes all of the functionality of the DateTime type along with time zone awareness."7 Go uses one type, time.Time, for an instant, a local reading and a date. C keeps an instant in a time_t and its fields in a struct tm. The Rust standard library has clocks and durations but no calendar.
The example files show these forms. Python compares an aware and a naive value. JavaScript shows a Date that changes, a field that rolls over and an invalid date. Java adds a period and a duration across the start of daylight saving time in New York. C# uses DateTimeOffset, DateOnly and TimeSpan. Go compares two time.Time values with Equal and with ==. Rust uses SystemTime, Instant and Duration. C converts a time_t to a struct tm and back. C++ uses the calendar types of std::chrono.
from datetime import date, datetime, timedelta, timezone
# An aware datetime has a zone, so it is an instant.
instant = datetime(2024, 3, 9, 12, 0, tzinfo=timezone.utc)
# A naive datetime has no zone. It is a reading of a wall clock.
wall = datetime(2024, 3, 9, 12, 0)
print(instant.tzinfo, wall.tzinfo)
# Equality between the two kinds is False, and an order test raises TypeError.
print(instant == wall)
try:
instant < wall
except TypeError as e:
print(type(e).__name__)
# The same instant at another offset is equal.
tokyo = instant.astimezone(timezone(timedelta(hours=9)))
print(tokyo.isoformat(), tokyo == instant)
print(instant.timestamp())
# A date has no time and no zone. 2024 is a leap year.
print(date(2024, 2, 28) + timedelta(days=1))
# A timedelta is an exact amount of time.
print(timedelta(hours=36), timedelta(minutes=90).total_seconds())
UTC None
False
TypeError
2024-03-09T21:00:00+09:00 True
1709985600.0
2024-02-29
1 day, 12:00:00 5400.0
- Verdict: stdlib. The module datetime has date, time, datetime and timedelta. A datetime with a tzinfo is aware and names an instant. A datetime without one is naive, and the program decides what it means. The module zoneinfo gives the zones of the IANA database.
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
// A sys_seconds is a time_point of the system clock: seconds since 1970-01-01 UTC.
sys_seconds t = sys_days{2024y / March / 9} + 12h;
std::cout << t << ' ' << t.time_since_epoch().count() << '\n';
// A year_month_day is a civil date. Plus 1 month can give a date that is not valid.
year_month_day next = 2024y / January / 31 + months{1};
std::cout << next.ok() << ' ' << year_month_day{2024y / February / last} << '\n';
// A duration has a type for its unit.
minutes m = 90min;
std::cout << m << ' ' << duration_cast<hours>(m) << ' ' << seconds{m}.count() << '\n';
}
2024-03-09 12:00:00 1709985600
0 2024-02-29
90min 1h 5400
- Verdict: stdlib. std::chrono has clocks, time_point and duration, and since C++20 calendar types such as year_month_day and time zones with zoned_time. A duration carries its unit in its type, so the compiler checks the conversions.
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// An Instant is a point on the time-line.
Instant i = Instant.parse("2024-03-09T12:00:00Z");
System.out.println(i + " " + i.getEpochSecond());
// A LocalDate has no time and no zone. Plus 1 month clamps to the end of February.
LocalDate jan31 = LocalDate.of(2024, 1, 31);
System.out.println(jan31.plusMonths(1));
// Daylight saving time starts in New York at 02:00 on 2024-03-10.
ZonedDateTime ny = LocalDateTime.of(2024, 3, 9, 12, 0).atZone(ZoneId.of("America/New_York"));
// A Period of 1 day keeps the wall clock time. A Duration of 24 hours does not.
System.out.println(ny.plus(Period.ofDays(1)));
System.out.println(ny.plus(Duration.ofHours(24)));
System.out.println(Period.between(jan31, LocalDate.of(2024, 3, 1)) + " " + Duration.ofMinutes(90));
}
}
2024-03-09T12:00:00Z 1709985600
2024-02-29
2024-03-10T12:00-04:00[America/New_York]
2024-03-10T13:00-04:00[America/New_York]
P1M1D PT1H30M
- Verdict: stdlib. The package java.time has Instant, LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, Duration and Period. All of them are immutable. The older java.util.Date and Calendar are mutable, and new code does not use them.
#include <stdio.h>
#include <time.h>
int main(void) {
// A time_t is a count of seconds since the epoch on POSIX systems.
time_t t = 1709985600;
struct tm *utc = gmtime(&t);
// tm_year counts from 1900, and tm_mon counts from 0.
printf("%d %d %d\n", utc->tm_year, utc->tm_mon, utc->tm_mday);
char buf[32];
strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", utc);
puts(buf);
// mktime normalizes fields that are out of range: February 30 is March 1.
struct tm feb = {.tm_year = 124, .tm_mon = 1, .tm_mday = 30, .tm_hour = 12, .tm_isdst = -1};
mktime(&feb);
printf("%d-%02d-%02d\n", feb.tm_year + 1900, feb.tm_mon + 1, feb.tm_mday);
// difftime gives the difference of two time_t values in seconds.
printf("%.0f\n", difftime(t + 5400, t));
return 0;
}
124 2 9
2024-03-09T12:00:00Z
2024-03-01
5400
- Verdict: stdlib. time.h has time_t for a calendar time, struct tm for its fields, and time, gmtime, localtime, mktime and strftime. The fields of struct tm start at 1900 for the year and at 0 for the month. There are no zone names other than the local zone of the process.
using System;
// A DateTimeOffset is a date and time with an offset from UTC, so it is an instant.
var utc = new DateTimeOffset(2024, 3, 9, 12, 0, 0, TimeSpan.Zero);
var tokyo = utc.ToOffset(TimeSpan.FromHours(9));
Console.WriteLine(utc.ToString("O") + " " + tokyo.ToString("O") + " " + (utc == tokyo));
Console.WriteLine(utc.ToUnixTimeSeconds());
// A DateTime without a kind is not tied to a zone.
var wall = new DateTime(2024, 3, 9, 12, 0, 0);
Console.WriteLine(wall.Kind);
// A DateOnly has no time. Plus 1 month clamps to the end of February.
var jan31 = new DateOnly(2024, 1, 31);
Console.WriteLine(jan31.AddMonths(1).ToString("yyyy-MM-dd"));
// A TimeSpan is an amount of time.
Console.WriteLine(TimeSpan.FromMinutes(90) + " " + TimeSpan.FromMinutes(90).TotalSeconds);
2024-03-09T12:00:00.0000000+00:00 2024-03-09T21:00:00.0000000+09:00 True
1709985600
Unspecified
2024-02-29
01:30:00 5400
- Verdict: stdlib. .NET has DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan and TimeZoneInfo. A DateTimeOffset names one instant. A DateTime has a Kind of Utc, Local or Unspecified, and two values with different kinds compare by their fields only.
// A Date holds a count of milliseconds since 1970-01-01T00:00:00Z.
// The month index starts at 0, so 2 is March.
const d = new Date(Date.UTC(2024, 2, 9, 12, 0));
console.log(d.toISOString(), d.getTime());
// A Date can change. Copy it before a change.
const copy = new Date(d.getTime());
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString(), copy.toISOString());
// A field that is out of range rolls over: February 30 is March 1.
console.log(new Date(Date.UTC(2024, 1, 30)).toISOString());
// The difference of two dates is a number of milliseconds.
console.log((d - copy) / 3600000);
// A date that is not valid holds NaN.
const bad = new Date("not a date");
console.log(Number.isNaN(bad.getTime()));
2024-03-09T12:00:00.000Z 1709985600000
2024-03-10T12:00:00.000Z 2024-03-09T12:00:00.000Z
2024-03-01T00:00:00.000Z
24
true
- Verdict: native. Date is an instant with millisecond precision, and its methods read it in UTC or in the local zone of the host. It is mutable, and its month index starts at 0. Temporal, which has Instant, PlainDate, ZonedDateTime and Duration, replaces it in newer engines.
package main
import (
"fmt"
"strings"
"time"
)
func main() {
// A time.Time is an instant with a location for display.
t := time.Date(2024, time.March, 9, 12, 0, 0, 0, time.UTC)
fmt.Println(t.Format(time.RFC3339), t.Unix())
// The same instant in another location. Equal compares instants, and == compares fields.
tokyo := t.In(time.FixedZone("JST", 9*60*60))
fmt.Println(tokyo.Format(time.RFC3339), t.Equal(tokyo), t == tokyo)
// AddDate normalizes: January 31 plus 1 month is February 31, which is March 2.
jan31 := time.Date(2024, time.January, 31, 0, 0, 0, 0, time.UTC)
fmt.Println(jan31.AddDate(0, 1, 0).Format(time.DateOnly))
// A time.Duration is a count of nanoseconds.
d := 90 * time.Minute
fmt.Println(d, d.Seconds())
// time.Now has a monotonic clock reading. Round(0) removes it.
now := time.Now()
fmt.Println(strings.Contains(now.String(), "m="), strings.Contains(now.Round(0).String(), "m="))
}
2024-03-09T12:00:00Z 1709985600
2024-03-09T21:00:00+09:00 true false
2024-03-02
1h30m0s 5400
true false
- Verdict: stdlib. The package time has Time, Duration and Location. A Time is an instant with a location, and the Time from time.Now also has a monotonic clock reading for elapsed time. There is no separate date type: a date is a Time at midnight.
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
fn main() {
// A SystemTime is a reading of the system clock. It has no calendar fields.
let t = UNIX_EPOCH + Duration::from_secs(1_709_985_600);
println!("{}", t.duration_since(UNIX_EPOCH).unwrap().as_secs());
// duration_since returns an error when the other time is later.
println!("{}", UNIX_EPOCH.duration_since(t).is_err());
println!("{}", SystemTime::now() > t);
// A Duration is an amount of time.
let d = Duration::from_secs(90 * 60);
println!("{:?} {}", d, d.as_secs_f64());
// An Instant is for elapsed time only. It has no epoch and no date.
let start = Instant::now();
println!("{}", start.elapsed() < Duration::from_secs(60));
}
1709985600
true
true
5400s 5400
true
- Verdict: stdlib. std::time has SystemTime, Instant and Duration, but no calendar dates, no time zones and no formatting. Programs use a crate such as chrono, time or jiff for dates.
Variations and related ideas
- Time scales. UTC follows the rotation of the Earth with leap seconds, and other scales do not. C++ has a clock for each scale, such as a "Clock for International Atomic Time (TAI)"2 and a "Clock for GPS time"2. See Leap seconds.
- Text forms. A program sends and stores a time as text in the formats of ISO 8601 and RFC 3339, such as
2024-03-09T12:00:00Z. See ISO 8601 and Parse and format a date. - Partial dates. Some values have only some fields: a month and a day for a birthday, or a year and a month for a card expiry date. Java has
MonthDay,YearMonth,MonthandDayOfWeek. In Java, "Month stores a month on its own."5 - Other calendars. Most libraries use the Gregorian calendar for computation and other calendars for display. Java has "the calendar neutral API"5 in the package
java.time.chrono, andTemporalhas a calendar in each date. - Elapsed time. A monotonic clock gives durations but no dates. See Measure elapsed time.
Pitfalls
- Months that start at 0. The JavaScript
Dateconstructor takes a month index: an "Integer value representing the month, beginning with 0 for January to 11 for December."11 Thusnew Date(2024, 1, 1)is 1 February. In C, the fieldtm_monofstruct tmcounts the "months since January"12, andtm_yearcounts the "years since 1900"12. - A mix of naive and aware values. A naive value has no zone, and "Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other time zone is purely up to the program"1. In Python, an order test between a naive and an aware value raises
TypeError, and an equality test is false. Keep instants aware, and convert at the edges of the program. - Mutable date objects. A JavaScript
Dateand a Javajava.util.Datecan change. A date in the field of an object changes when other code calls a setter on it. Copy the value, or use immutable types such asjava.timeandTemporal. - Field equality for instants. Two values for one instant can have different fields. Go says: "In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading."6 The Go example shows that
==is false for one instant in two zones. - The wall clock for elapsed time. The system clock can move back. For Rust
SystemTime, "Distinct from the Instant type, this time measurement is not monotonic."9 Measure elapsed time with a monotonic clock. - The local zone of the machine. A function that uses the local zone, such as C
localtimeor a JavaScriptDategetter withoutUTCin its name, gives different results on different machines. Tests that pass on one machine can fail on a server in UTC. Give the zone explicitly.
Cost
| Value | Range | Precision |
|---|---|---|
32-bit time_t |
from 1901-12-13 to 2038-01-1913 | 1 second |
64-bit time_t |
about 292.3 billion years in both directions13 | 1 second |
JavaScript Date |
from April 20, 271821 BC to September 13, 275760 AD4 | 1 millisecond |
Python datetime |
the years 1 to 99991 | 1 microsecond |
Go time.Time, Java Instant |
far beyond the dates of most programs | 1 nanosecond |
An instant as one integer is cheap to store, compare and sort. A conversion to fields costs more, because it needs the calendar rules and, for a local time, the rules of the zone. A 32-bit count of seconds has a hard limit: "One second after 2038-01-19T03:14:07Z this representation will overflow in what is known as the year 2038 problem"13. Python sets its limits in constants: "MINYEAR is 1."1 and "MAXYEAR is 9999."1
History
The first Unix systems counted time from a recent epoch. The first edition of the Unix Programmer's Manual, from 3 November 1971, says that "time returns the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second."13 Later versions moved the epoch to 1970 and counted whole seconds, and C and POSIX took that count as time_t, with struct tm for the fields3.
The first libraries mixed the kinds of values. Java 1.0 put an instant and its fields into one class. Today the documentation says: "The class Date represents a specific instant in time, with millisecond precision. Prior to JDK 1.1, the class Date had two additional functions."14 Java later added Calendar, and then JSR 310, which says: "This JSR will provide a new and improved date and time API for Java."15 Its final release was on 4 March 201415, as the package java.time.
Python added the module datetime in Python 2.3: "A set of standard date/time types has been added in the new datetime module."16 "Python 2.3 was released on July 29, 2003."16 C++ added std::chrono with clocks and durations in C++11, and calendar dates and time zones in C++202. In JavaScript, the Temporal proposal reached Stage 4 at TC39, and it shipped in Firefox 139 on 2025-05-27, in Chrome 144 on 2026-01-13 and in Node 26 on 2026-05-0517.
References
- datetime, Basic date and time types, The Python Standard Library, Aware and naive objects; Constants; Available types
- Date and time library, cppreference.com, Clocks; Time point; Calendar; Time zone
- POSIX.1-2024, Base Definitions, General Concepts, 4.19 Seconds Since the Epoch
- Date, MDN Web Docs, Description; The epoch, timestamps, and invalid date
- Package java.time, Java SE 25 API, Description; Dates and Times; Duration and Period
- Package time, Go standard library, Monotonic Clocks; type Time
- Choose between DateTime, DateOnly, DateTimeOffset, TimeSpan, TimeOnly, and TimeZoneInfo, .NET, The DateTimeOffset structure
- Struct Instant, The Rust Standard Library, Description
- Struct SystemTime, The Rust Standard Library, Description
- Temporal, MDN Web Docs, Description
- Date() constructor, MDN Web Docs, Parameters
- tm, cppreference.com, Member objects
- Unix time, Wikipedia, Range of representable times; History
- Class Date, Java SE 25 API, Description
- JSR 310, Date and Time API, Java Community Process, Description; Stage timeline
- What's New in Python 2.3, Introduction; Other New, Improved, and Deprecated Modules
- Temporal proposal, TC39, Status
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4W6JX1 Edit this page History Report an error Markdown