Taskintro
Compute the difference of two dates
Also called days between two dates, date difference, date diff, number of days between dates, subtract two dates, DAYS.between, DayNumber, timedelta days.
Count the days from one calendar date to another. Subtract dates with no time zone or in UTC, because a local day can have 23 or 25 hours and a period in months is not a count of days.
- Evidence
- Code in 10 languages
Task
Count the days from one calendar date to another. A date here has no time of day and no time zone, such as 2024-03-10.
The contract days_between(start_year, start_month, start_day, end_year, end_month, end_day) returns the end date minus the start date as a number of days. The result is 0 for the same date, 1 for the next date, and negative when the end date is before the start date. The dates use the proleptic Gregorian calendar for the years 1 to 9999.
The usual method gives each date a day number and subtracts the two numbers. A day number counts the days from a fixed date, such as 1970-01-01 or 0001-01-01. The difference does not depend on the fixed date.
Solutions
Each solution subtracts two dates with no time zone, or two midnights in UTC. In UTC every day has 86400 seconds, so a count of seconds divided by 86400 is exact. A count from two local times is not exact (see the pitfalls).
- Python.
date2 - date1gives atimedelta, and itsdaysattribute is the count. Adatehas no time and no time zone.date.toordinal()gives a day number with 0001-01-01 as day 1. - JavaScript.
Datehas no type for a date alone, so the solution takes midnight UTC of each date, subtracts the two time values in milliseconds and divides by 86400000. It sets the year withsetUTCFullYear, becauseDate.UTCreads the years 0 to 99 as 1900 to 1999. Where the Temporal API is available,Temporal.PlainDatehasuntilandsince. - TypeScript. The same code as JavaScript, with the type
number. - Java.
ChronoUnit.DAYS.between(start, end)returns along. The documentation ofLocalDate.untilsays thatstart.until(end, DAYS)is the same, and that "The calculation returns a whole number, representing the number of complete units between the two dates."Period.betweenis not a count of days (see the pitfalls). - C#.
DateOnly.DayNumberis the number of days since January 1, 0001. The solution returnsend.DayNumber - start.DayNumber.(end - start).Dayson twoDateTimevalues also works when both are midnight of the same kind. - Go. The solution makes both dates with
time.Date(..., time.UTC)and divides the difference ofUnix()by 86400. It does not useend.Sub(start), because atime.Durationis anint64count of nanoseconds and holds about 292 years. - Rust. The standard library has no calendar date. The solution computes a day number with the
days_from_civilalgorithm of Howard Hinnant and subtracts. A crate such aschronoorjiffhas a date type with this subtraction. - C.
mktimereads the fields as local time. The solution uses the samedays_from_civilarithmetic as Rust inlong long. - C++.
std::chrono::sys_daysis atime_pointwith a unit of one day. The solution converts eachyear_month_daytosys_days, and(end - start).count()is the number of days. - Bash. GNU
date -u -d 2024-03-10 +%sgives the seconds at midnight UTC. The solution subtracts the two values and divides by 86400. The-uoption is necessary (see the pitfalls).
A date with no time zone gives the same count on each system:
from datetime import date
print((date(2024, 3, 1) - date(2024, 1, 1)).days)
print((date(2023, 3, 1) - date(2024, 3, 1)).days)
print((date(9999, 12, 31) - date(1, 1, 1)).days)
60
-366
3652058
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
same-day,next-dayandend-before-start: the result is 0, 1 and -1.common-yearandleap-year: 2023 has 365 days and 2024 has 366.across-a-dst-change: 2024-03-09 to 2024-03-11 is 2 days. In New York, 2024-03-10 had only 23 hours, but a date has no time zone.across-leap-dayandmonth-end-to-next-month: 2024-01-31 to 2024-03-01 is 30 days, because February 2024 has 29 days.year-1900-is-not-leapandyear-2000-is-leap: 1900 has 365 days and 2000 has 366.400-years: 400 Gregorian years always have 146097 days.across-the-epoch: 1969-12-31 to 1970-01-01 is 1 day. A day number before 1970 is negative, and the subtraction is the same.gregorian-reform-gap: 1582-10-04 to 1582-10-15 is 11 days in the proleptic Gregorian calendar. In the countries that changed calendar in October 1582, these two dates were consecutive days.more-than-292-years: 1700-01-01 to 2300-01-01 is 219145 days, more than a Gotime.Durationholds.whole-rangeandwhole-range-backward: 0001-01-01 to 9999-12-31 is 3652058 days, and the other direction is -3652058.year-99: 0099-12-31 to 0100-01-01 is 1 day. An API that reads the year 99 as 1999 gives a wrong count.
Pitfalls
- Local days are not 24 hours. Two local midnights in a time zone with daylight saving time are not always a multiple of 86400 seconds apart. In New York, the clocks went from 02:00 to 03:00 on 2024-03-10:
This code runs but gives a wrong answer on purpose.
process.env.TZ = "America/New_York";
const start = new Date(2024, 2, 9);
const end = new Date(2024, 2, 11);
const days = (end - start) / (24 * 60 * 60 * 1000);
console.log(days);
console.log(Math.floor(days));
1.9583333333333333
1
date -d without -u reads the dates in the local time zone, and the shell division drops the 23 hours:
This code runs but gives a wrong answer on purpose.
export TZ=America/New_York
start=$(date -d 2024-03-10 +%s)
end=$(date -d 2024-03-11 +%s)
echo $(( end - start ))
echo $(( (end - start) / 86400 ))
82800
0
- The days field of a duration is not rounded to the nearest day. Python keeps a
timedeltaas days, seconds and microseconds with0 <= seconds < 3600*24, sodaysgoes toward the past for a negative difference. The difference of two date-times 12 hours apart hasdays0 in one direction and -1 in the other:
This code runs but gives a wrong answer on purpose.
from datetime import datetime
evening = datetime(2024, 3, 1, 18, 0)
morning = datetime(2024, 3, 2, 6, 0)
print((morning - evening).days)
print((evening - morning).days)
print(evening - morning)
0
-1
-1 day, 12:00:00
The .NET documentation says: "The Days property represents whole days, whereas the TotalDays property represents whole and fractional days." For the same two times, Days is 0 in both directions:
This code runs but gives a wrong answer on purpose.
var evening = new DateTime(2024, 3, 1, 18, 0, 0);
var morning = new DateTime(2024, 3, 2, 6, 0, 0);
Console.WriteLine((morning - evening).Days);
Console.WriteLine((evening - morning).Days);
Console.WriteLine((evening - morning).Hours);
0
0
-12
Subtract dates, or midnights in UTC, and the count is exact.
- A period is not a count of days. Java
Period.betweengives years, months and days, andgetDays()is only the days part. From 2024-01-01 to 2024-03-01 the period is two months and zero days:
This code runs but gives a wrong answer on purpose.
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024, 1, 1);
LocalDate end = LocalDate.of(2024, 3, 1);
Period period = Period.between(start, end);
System.out.println(period);
System.out.println(period.getDays());
System.out.println(ChronoUnit.DAYS.between(start, end));
}
}
P2M
0
60
- A duration can overflow. Go
Subreturns the maximumDurationwhen the result does not fit, so the count of days is wrong with no error:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Date(1700, time.January, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2300, time.January, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(end.Sub(start))
fmt.Println(int64(end.Sub(start).Hours() / 24))
fmt.Println((end.Unix() - start.Unix()) / 86400)
}
2562047h47m16.854775807s
106751
219145
- Two-digit years.
Date.UTCreads the years 0 to 99 as 1900 to 1999, so the year 99 becomes 1999:
This code runs but gives a wrong answer on purpose.
const msPerDay = 24 * 60 * 60 * 1000;
console.log(new Date(Date.UTC(99, 11, 31)).toISOString());
console.log((Date.UTC(100, 0, 1) - Date.UTC(99, 11, 31)) / msPerDay);
1999-12-31T00:00:00.000Z
-693959
Related tasks
- Add days to a date: the inverse operation, a date plus a number of days.
- Find the day of the week: a day number modulo 7 gives the weekday.
- Check for a leap year: the rule that makes a year 365 or 366 days.
- Measure elapsed time: the time between two instants with a monotonic clock.
- Get a Unix timestamp: a date as seconds since 1970.
- Convert between time zones: the local date of an instant.
See Calendar arithmetic for the rules of the Gregorian calendar.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
from datetime import date
def days_between(
start_year: int, start_month: int, start_day: int, end_year: int, end_month: int, end_day: int
) -> int:
"""Return the number of days from the start date to the end date."""
return (date(end_year, end_month, end_day) - date(start_year, start_month, start_day)).days
test_diff.py 43 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
from datetime import date, timedelta
import pytest
from diff import days_between
CASES = [
("same-day", (2024, 3, 10, 2024, 3, 10), 0),
("next-day", (2024, 3, 10, 2024, 3, 11), 1),
("common-year", (2023, 1, 1, 2024, 1, 1), 365),
("leap-year", (2024, 1, 1, 2025, 1, 1), 366),
("end-before-start", (2024, 3, 11, 2024, 3, 10), -1),
("across-a-dst-change", (2024, 3, 9, 2024, 3, 11), 2),
("across-leap-day", (2024, 2, 28, 2024, 3, 1), 2),
("month-end-to-next-month", (2024, 1, 31, 2024, 3, 1), 30),
("year-1900-is-not-leap", (1900, 1, 1, 1901, 1, 1), 365),
("year-2000-is-leap", (2000, 1, 1, 2001, 1, 1), 366),
("400-years", (2000, 1, 1, 2400, 1, 1), 146097),
("across-the-epoch", (1969, 12, 31, 1970, 1, 1), 1),
("gregorian-reform-gap", (1582, 10, 4, 1582, 10, 15), 11),
("more-than-292-years", (1700, 1, 1, 2300, 1, 1), 219145),
("whole-range", (1, 1, 1, 9999, 12, 31), 3652058),
("whole-range-backward", (9999, 12, 31, 1, 1, 1), -3652058),
("year-99", (99, 12, 31, 100, 1, 1), 1),
]
@pytest.mark.parametrize(("name", "fields", "want"), CASES, ids=[c[0] for c in CASES])
def test_days_between(name, fields, want):
assert days_between(*fields) == want
def test_ordinal_gives_the_same_count():
start, end = date(1, 1, 1), date(9999, 12, 31)
assert end.toordinal() - start.toordinal() == days_between(1, 1, 1, 9999, 12, 31)
def test_days_drops_the_time_of_day():
assert timedelta(hours=-1).days == -1
assert timedelta(hours=23).days == 0
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
#ifndef DAYS_BETWEEN_HPP
#define DAYS_BETWEEN_HPP
#include <chrono>
// Returns the number of days from the start date to the end date. sys_days
// counts whole days from 1970-01-01, so the difference is a count of days.
inline long long days_between(int start_year, int start_month, int start_day, int end_year, int end_month, int end_day) {
using namespace std::chrono;
const sys_days start{year{start_year} / month{static_cast<unsigned>(start_month)} / day{static_cast<unsigned>(start_day)}};
const sys_days end{year{end_year} / month{static_cast<unsigned>(end_month)} / day{static_cast<unsigned>(end_day)}};
return (end - start).count();
}
#endif
test_diff.cpp 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
#include <chrono>
#include <cstdio>
#include "diff.hpp"
namespace {
struct test_case {
const char* name;
int start_year, start_month, start_day, end_year, end_month, end_day;
long long want;
};
const test_case cases[] = {
{"same-day", 2024, 3, 10, 2024, 3, 10, 0},
{"next-day", 2024, 3, 10, 2024, 3, 11, 1},
{"common-year", 2023, 1, 1, 2024, 1, 1, 365},
{"leap-year", 2024, 1, 1, 2025, 1, 1, 366},
{"end-before-start", 2024, 3, 11, 2024, 3, 10, -1},
{"across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2},
{"across-leap-day", 2024, 2, 28, 2024, 3, 1, 2},
{"month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30},
{"year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365},
{"year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366},
{"400-years", 2000, 1, 1, 2400, 1, 1, 146097},
{"across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1},
{"gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11},
{"more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145},
{"whole-range", 1, 1, 1, 9999, 12, 31, 3652058},
{"whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058},
{"year-99", 99, 12, 31, 100, 1, 1, 1},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const long long got = days_between(c.start_year, c.start_month, c.start_day, c.end_year, c.end_month, c.end_day);
if (got != c.want) {
std::printf("FAIL %s: got %lld, want %lld\n", c.name, got, c.want);
++failures;
}
}
using namespace std::chrono;
const auto months_apart = (2024y / March) - (2024y / January);
if (months_apart.count() != 2) {
std::printf("FAIL year_month difference\n");
++failures;
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/** Counts the days between two dates. */
public final class DateDiff {
private DateDiff() {}
/** Returns the number of days from the start date to the end date. */
public static long daysBetween(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay) {
LocalDate start = LocalDate.of(startYear, startMonth, startDay);
LocalDate end = LocalDate.of(endYear, endMonth, endDay);
return ChronoUnit.DAYS.between(start, end);
}
}
DateDiffTest.java 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import java.time.Period;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class DateDiffTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("same-day", 2024, 3, 10, 2024, 3, 10, 0L),
Arguments.of("next-day", 2024, 3, 10, 2024, 3, 11, 1L),
Arguments.of("common-year", 2023, 1, 1, 2024, 1, 1, 365L),
Arguments.of("leap-year", 2024, 1, 1, 2025, 1, 1, 366L),
Arguments.of("end-before-start", 2024, 3, 11, 2024, 3, 10, -1L),
Arguments.of("across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2L),
Arguments.of("across-leap-day", 2024, 2, 28, 2024, 3, 1, 2L),
Arguments.of("month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30L),
Arguments.of("year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365L),
Arguments.of("year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366L),
Arguments.of("400-years", 2000, 1, 1, 2400, 1, 1, 146097L),
Arguments.of("across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1L),
Arguments.of("gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11L),
Arguments.of("more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145L),
Arguments.of("whole-range", 1, 1, 1, 9999, 12, 31, 3652058L),
Arguments.of("whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058L),
Arguments.of("year-99", 99, 12, 31, 100, 1, 1, 1L)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void daysBetween(String name, int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay, long want) {
assertEquals(want, DateDiff.daysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay));
}
@Test
void periodGetDaysIsOnlyTheDayPart() {
Period period = Period.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 3, 1));
assertEquals(2, period.getMonths());
assertEquals(0, period.getDays());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
#include "diff.h"
// The formula is from Howard Hinnant, "chrono-Compatible Low-Level Date
// Algorithms". It needs no time zone and no time_t, so it also works for
// years before 1970 and before 1900.
long long days_from_civil(long long year, int month, int day) {
long long y = month <= 2 ? year - 1 : year;
long long era = (y >= 0 ? y : y - 399) / 400;
long long yoe = y - era * 400;
long long mp = (month + 9) % 12;
long long doy = (153 * mp + 2) / 5 + day - 1;
long long doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
long long days_between(int start_year, int start_month, int start_day, int end_year, int end_month, int end_day) {
return days_from_civil(end_year, end_month, end_day) - days_from_civil(start_year, start_month, start_day);
}
diff.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
#ifndef DAYS_BETWEEN_H
#define DAYS_BETWEEN_H
// Returns the number of days from 1970-01-01 to a date of the proleptic
// Gregorian calendar.
long long days_from_civil(long long year, int month, int day);
// Returns the number of days from the start date to the end date.
long long days_between(int start_year, int start_month, int start_day, int end_year, int end_month, int end_day);
#endif
test_diff.c 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
#include "diff.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
int start_year, start_month, start_day, end_year, end_month, end_day;
long long want;
};
static const struct test_case cases[] = {
{"same-day", 2024, 3, 10, 2024, 3, 10, 0},
{"next-day", 2024, 3, 10, 2024, 3, 11, 1},
{"common-year", 2023, 1, 1, 2024, 1, 1, 365},
{"leap-year", 2024, 1, 1, 2025, 1, 1, 366},
{"end-before-start", 2024, 3, 11, 2024, 3, 10, -1},
{"across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2},
{"across-leap-day", 2024, 2, 28, 2024, 3, 1, 2},
{"month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30},
{"year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365},
{"year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366},
{"400-years", 2000, 1, 1, 2400, 1, 1, 146097},
{"across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1},
{"gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11},
{"more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145},
{"whole-range", 1, 1, 1, 9999, 12, 31, 3652058},
{"whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058},
{"year-99", 99, 12, 31, 100, 1, 1, 1},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
long long got = days_between(c->start_year, c->start_month, c->start_day, c->end_year, c->end_month, c->end_day);
if (got != c->want) {
printf("FAIL %s: got %lld, want %lld\n", c->name, got, c->want);
failures++;
}
}
if (days_from_civil(1970, 1, 1) != 0 || days_from_civil(1, 1, 1) != -719162) {
printf("FAIL days_from_civil\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
using System;
/// <summary>Counts the days between two dates.</summary>
public static class DateDiff
{
/// <summary>Returns the number of days from the start date to the end date.</summary>
public static int DaysBetween(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay)
{
var start = new DateOnly(startYear, startMonth, startDay);
var end = new DateOnly(endYear, endMonth, endDay);
return end.DayNumber - start.DayNumber;
}
}
DateDiffTests.cs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
using System;
using Xunit;
public sealed class DateDiffTests
{
public static TheoryData<string, int, int, int, int, int, int, int> Cases => new()
{
{ "same-day", 2024, 3, 10, 2024, 3, 10, 0 },
{ "next-day", 2024, 3, 10, 2024, 3, 11, 1 },
{ "common-year", 2023, 1, 1, 2024, 1, 1, 365 },
{ "leap-year", 2024, 1, 1, 2025, 1, 1, 366 },
{ "end-before-start", 2024, 3, 11, 2024, 3, 10, -1 },
{ "across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2 },
{ "across-leap-day", 2024, 2, 28, 2024, 3, 1, 2 },
{ "month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30 },
{ "year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365 },
{ "year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366 },
{ "400-years", 2000, 1, 1, 2400, 1, 1, 146097 },
{ "across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1 },
{ "gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11 },
{ "more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145 },
{ "whole-range", 1, 1, 1, 9999, 12, 31, 3652058 },
{ "whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058 },
{ "year-99", 99, 12, 31, 100, 1, 1, 1 },
};
[Theory]
[MemberData(nameof(Cases))]
public void DaysBetween(string name, int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay, int want)
{
Assert.NotNull(name);
Assert.Equal(want, DateDiff.DaysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay));
}
[Fact]
public void TimeSpanDaysDropsThePartialDay()
{
var span = new DateTime(2024, 3, 2, 6, 0, 0) - new DateTime(2024, 3, 1, 18, 0, 0);
Assert.Equal(0, span.Days);
Assert.Equal(0.5, span.TotalDays);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/**
* Returns the milliseconds from the epoch to midnight UTC of a date.
* setUTCFullYear takes the year as it is. Date.UTC reads the years 0 to 99 as 1900 to 1999.
*/
function utcMidnight(year, month, day) {
const date = new Date(0);
date.setUTCFullYear(year, month - 1, day);
return date.getTime();
}
/**
* Returns the number of days from the start date to the end date.
* In UTC each day has exactly 86 400 000 ms, so the division is exact.
*/
export function daysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay) {
return (utcMidnight(endYear, endMonth, endDay) - utcMidnight(startYear, startMonth, startDay)) / MS_PER_DAY;
}
diff.test.js 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { daysBetween } from "./diff.js";
const cases = [
["same-day", [2024, 3, 10, 2024, 3, 10], 0],
["next-day", [2024, 3, 10, 2024, 3, 11], 1],
["common-year", [2023, 1, 1, 2024, 1, 1], 365],
["leap-year", [2024, 1, 1, 2025, 1, 1], 366],
["end-before-start", [2024, 3, 11, 2024, 3, 10], -1],
["across-a-dst-change", [2024, 3, 9, 2024, 3, 11], 2],
["across-leap-day", [2024, 2, 28, 2024, 3, 1], 2],
["month-end-to-next-month", [2024, 1, 31, 2024, 3, 1], 30],
["year-1900-is-not-leap", [1900, 1, 1, 1901, 1, 1], 365],
["year-2000-is-leap", [2000, 1, 1, 2001, 1, 1], 366],
["400-years", [2000, 1, 1, 2400, 1, 1], 146097],
["across-the-epoch", [1969, 12, 31, 1970, 1, 1], 1],
["gregorian-reform-gap", [1582, 10, 4, 1582, 10, 15], 11],
["more-than-292-years", [1700, 1, 1, 2300, 1, 1], 219145],
["whole-range", [1, 1, 1, 9999, 12, 31], 3652058],
["whole-range-backward", [9999, 12, 31, 1, 1, 1], -3652058],
["year-99", [99, 12, 31, 100, 1, 1], 1],
];
for (const [name, fields, want] of cases) {
test(name, () => {
const [startYear, startMonth, startDay, endYear, endMonth, endDay] = fields;
assert.equal(daysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay), want);
});
}
test("Date.UTC reads year 99 as 1999", () => {
assert.equal((Date.UTC(100, 0, 1) - Date.UTC(99, 11, 31)) / 86400000, -693959);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/**
* Returns the milliseconds from the epoch to midnight UTC of a date.
* setUTCFullYear takes the year as it is. Date.UTC reads the years 0 to 99 as 1900 to 1999.
*/
function utcMidnight(year: number, month: number, day: number): number {
const date = new Date(0);
date.setUTCFullYear(year, month - 1, day);
return date.getTime();
}
/**
* Returns the number of days from the start date to the end date.
* In UTC each day has exactly 86 400 000 ms, so the division is exact.
*/
export function daysBetween(startYear: number, startMonth: number, startDay: number, endYear: number, endMonth: number, endDay: number): number {
return (utcMidnight(endYear, endMonth, endDay) - utcMidnight(startYear, startMonth, startDay)) / MS_PER_DAY;
}
diff.test.ts 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { daysBetween } from "./diff.ts";
const cases: [string, [number, number, number, number, number, number], number][] = [
["same-day", [2024, 3, 10, 2024, 3, 10], 0],
["next-day", [2024, 3, 10, 2024, 3, 11], 1],
["common-year", [2023, 1, 1, 2024, 1, 1], 365],
["leap-year", [2024, 1, 1, 2025, 1, 1], 366],
["end-before-start", [2024, 3, 11, 2024, 3, 10], -1],
["across-a-dst-change", [2024, 3, 9, 2024, 3, 11], 2],
["across-leap-day", [2024, 2, 28, 2024, 3, 1], 2],
["month-end-to-next-month", [2024, 1, 31, 2024, 3, 1], 30],
["year-1900-is-not-leap", [1900, 1, 1, 1901, 1, 1], 365],
["year-2000-is-leap", [2000, 1, 1, 2001, 1, 1], 366],
["400-years", [2000, 1, 1, 2400, 1, 1], 146097],
["across-the-epoch", [1969, 12, 31, 1970, 1, 1], 1],
["gregorian-reform-gap", [1582, 10, 4, 1582, 10, 15], 11],
["more-than-292-years", [1700, 1, 1, 2300, 1, 1], 219145],
["whole-range", [1, 1, 1, 9999, 12, 31], 3652058],
["whole-range-backward", [9999, 12, 31, 1, 1, 1], -3652058],
["year-99", [99, 12, 31, 100, 1, 1], 1],
];
for (const [name, fields, want] of cases) {
test(name, () => {
const [startYear, startMonth, startDay, endYear, endMonth, endDay] = fields;
assert.equal(daysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay), want);
});
}
test("Date.UTC reads year 99 as 1999", () => {
assert.equal((Date.UTC(100, 0, 1) - Date.UTC(99, 11, 31)) / 86400000, -693959);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
// Package diff counts the days between two dates.
package diff
import "time"
// DaysBetween returns the number of days from the start date to the end date.
// It subtracts Unix seconds and not two times with Sub, because a
// time.Duration holds about 292 years at most.
func DaysBetween(startYear, startMonth, startDay, endYear, endMonth, endDay int) int64 {
start := time.Date(startYear, time.Month(startMonth), startDay, 0, 0, 0, 0, time.UTC)
end := time.Date(endYear, time.Month(endMonth), endDay, 0, 0, 0, 0, time.UTC)
return (end.Unix() - start.Unix()) / (24 * 60 * 60)
}
diff_test.go 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
package diff
import (
"math"
"testing"
"time"
)
var cases = []struct {
name string
startYear, startMonth, startDay, endYear, endMonth, endDay int
want int64
}{
{"same-day", 2024, 3, 10, 2024, 3, 10, 0},
{"next-day", 2024, 3, 10, 2024, 3, 11, 1},
{"common-year", 2023, 1, 1, 2024, 1, 1, 365},
{"leap-year", 2024, 1, 1, 2025, 1, 1, 366},
{"end-before-start", 2024, 3, 11, 2024, 3, 10, -1},
{"across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2},
{"across-leap-day", 2024, 2, 28, 2024, 3, 1, 2},
{"month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30},
{"year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365},
{"year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366},
{"400-years", 2000, 1, 1, 2400, 1, 1, 146097},
{"across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1},
{"gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11},
{"more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145},
{"whole-range", 1, 1, 1, 9999, 12, 31, 3652058},
{"whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058},
{"year-99", 99, 12, 31, 100, 1, 1, 1},
}
func TestDaysBetween(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := DaysBetween(c.startYear, c.startMonth, c.startDay, c.endYear, c.endMonth, c.endDay); got != c.want {
t.Fatalf("got %d, want %d", got, c.want)
}
})
}
}
func TestSubSaturates(t *testing.T) {
start := time.Date(1700, time.January, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2300, time.January, 1, 0, 0, 0, 0, time.UTC)
if got := end.Sub(start); got != time.Duration(math.MaxInt64) {
t.Fatalf("got %v", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
/// Returns the number of days from 1970-01-01 to a date of the proleptic
/// Gregorian calendar. The formula is from Howard Hinnant, "chrono-Compatible
/// Low-Level Date Algorithms".
pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// Returns the number of days from the start date to the end date.
pub fn days_between(
start_year: i64,
start_month: i64,
start_day: i64,
end_year: i64,
end_month: i64,
end_day: i64,
) -> i64 {
days_from_civil(end_year, end_month, end_day) - days_from_civil(start_year, start_month, start_day)
}
tests/diff_test.rs 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
use algo_compute_the_difference_of_two_dates::{days_between, days_from_civil};
#[allow(clippy::type_complexity)]
const CASES: &[(&str, i64, i64, i64, i64, i64, i64, i64)] = &[
("same-day", 2024, 3, 10, 2024, 3, 10, 0),
("next-day", 2024, 3, 10, 2024, 3, 11, 1),
("common-year", 2023, 1, 1, 2024, 1, 1, 365),
("leap-year", 2024, 1, 1, 2025, 1, 1, 366),
("end-before-start", 2024, 3, 11, 2024, 3, 10, -1),
("across-a-dst-change", 2024, 3, 9, 2024, 3, 11, 2),
("across-leap-day", 2024, 2, 28, 2024, 3, 1, 2),
("month-end-to-next-month", 2024, 1, 31, 2024, 3, 1, 30),
("year-1900-is-not-leap", 1900, 1, 1, 1901, 1, 1, 365),
("year-2000-is-leap", 2000, 1, 1, 2001, 1, 1, 366),
("400-years", 2000, 1, 1, 2400, 1, 1, 146097),
("across-the-epoch", 1969, 12, 31, 1970, 1, 1, 1),
("gregorian-reform-gap", 1582, 10, 4, 1582, 10, 15, 11),
("more-than-292-years", 1700, 1, 1, 2300, 1, 1, 219145),
("whole-range", 1, 1, 1, 9999, 12, 31, 3652058),
("whole-range-backward", 9999, 12, 31, 1, 1, 1, -3652058),
("year-99", 99, 12, 31, 100, 1, 1, 1),
];
#[test]
fn cases() {
for &(name, sy, sm, sd, ey, em, ed, want) in CASES {
assert_eq!(days_between(sy, sm, sd, ey, em, ed), want, "{name}");
}
}
#[test]
fn known_day_numbers() {
assert_eq!(days_from_civil(1970, 1, 1), 0);
assert_eq!(days_from_civil(1969, 12, 31), -1);
assert_eq!(days_from_civil(2000, 3, 1), 11_017);
assert_eq!(days_from_civil(1, 1, 1), -719_162);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
# days_between START_YEAR START_MONTH START_DAY END_YEAR END_MONTH END_DAY
# Prints the number of days from the start date to the end date. It needs GNU
# date. The -u option reads both dates as midnight UTC, so every day has
# 86400 seconds and the division is exact.
days_between() {
local start end
start=$(date -u -d "$(printf '%04d-%02d-%02d' "$1" "$2" "$3")" +%s) || return 1
end=$(date -u -d "$(printf '%04d-%02d-%02d' "$4" "$5" "$6")" +%s) || return 1
echo $(( (end - start) / 86400 ))
}
test_diff.bats 25 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-difference-of-two-dates/.
setup() {
source "$BATS_TEST_DIRNAME/diff.sh"
}
@test "same-day" { run days_between 2024 3 10 2024 3 10; [ "$status" -eq 0 ]; [ "$output" = 0 ]; }
@test "next-day" { run days_between 2024 3 10 2024 3 11; [ "$status" -eq 0 ]; [ "$output" = 1 ]; }
@test "common-year" { run days_between 2023 1 1 2024 1 1; [ "$status" -eq 0 ]; [ "$output" = 365 ]; }
@test "leap-year" { run days_between 2024 1 1 2025 1 1; [ "$status" -eq 0 ]; [ "$output" = 366 ]; }
@test "end-before-start" { run days_between 2024 3 11 2024 3 10; [ "$status" -eq 0 ]; [ "$output" = -1 ]; }
@test "across-a-dst-change" { run days_between 2024 3 9 2024 3 11; [ "$status" -eq 0 ]; [ "$output" = 2 ]; }
@test "across-leap-day" { run days_between 2024 2 28 2024 3 1; [ "$status" -eq 0 ]; [ "$output" = 2 ]; }
@test "month-end-to-next-month" { run days_between 2024 1 31 2024 3 1; [ "$status" -eq 0 ]; [ "$output" = 30 ]; }
@test "year-1900-is-not-leap" { run days_between 1900 1 1 1901 1 1; [ "$status" -eq 0 ]; [ "$output" = 365 ]; }
@test "year-2000-is-leap" { run days_between 2000 1 1 2001 1 1; [ "$status" -eq 0 ]; [ "$output" = 366 ]; }
@test "400-years" { run days_between 2000 1 1 2400 1 1; [ "$status" -eq 0 ]; [ "$output" = 146097 ]; }
@test "across-the-epoch" { run days_between 1969 12 31 1970 1 1; [ "$status" -eq 0 ]; [ "$output" = 1 ]; }
@test "gregorian-reform-gap" { run days_between 1582 10 4 1582 10 15; [ "$status" -eq 0 ]; [ "$output" = 11 ]; }
@test "more-than-292-years" { run days_between 1700 1 1 2300 1 1; [ "$status" -eq 0 ]; [ "$output" = 219145 ]; }
@test "whole-range" { run days_between 1 1 1 9999 12 31; [ "$status" -eq 0 ]; [ "$output" = 3652058 ]; }
@test "whole-range-backward" { run days_between 9999 12 31 1 1 1; [ "$status" -eq 0 ]; [ "$output" = -3652058 ]; }
@test "year-99" { run days_between 99 12 31 100 1 1; [ "$status" -eq 0 ]; [ "$output" = 1 ]; }
References
- The Python Standard Library, datetime, timedelta objects; Supported operations of date (timedelta = date1 - date2); Supported operations of datetime
- MDN Web Docs, Date.UTC(), Description
- MDN Web Docs, Date.prototype.setUTCFullYear(), Description
- TC39 Temporal proposal, Temporal.PlainDate, date.until(other, options); date.since(other, options)
- Java SE 25 API, java.time.temporal.ChronoUnit, DAYS
- Java SE 25 API, java.time.LocalDate, until(Temporal, TemporalUnit); until(ChronoLocalDate)
- Java SE 25 API, java.time.Period, between(LocalDate, LocalDate); getDays()
- .NET API reference, DateOnly.DayNumber, Definition
- .NET API reference, TimeSpan.Days, Remarks
- Go standard library, time, func (Time) Sub; func (Time) Unix; type Duration
- cppreference.com, std::chrono::system_clock, sys_time, sys_days
- Howard Hinnant, chrono-Compatible Low-Level Date Algorithms, days_from_civil
- Linux manual page, date(1), -d, --date; -u, --utc
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 |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag RPTZX9 Edit this page History Report an error Markdown