Taskintro
Add days to a date
Also called date arithmetic, add months to a date, add years to a date, add a period, date plus days, subtract days from a date, next month, plusDays, AddDays, AddDate.
Add days, months and years to a calendar date. Months and years need a rule for the end of the month, and a day in a time zone with daylight saving time is not always 24 hours.
- Evidence
- Code in 10 languages
Task
Add a number of days, months and years to a calendar date, or subtract them. A date here has no time of day and no time zone, such as 2024-01-31.
Days are a fixed unit of the calendar. Months and years are not: a month has 28 to 31 days, and a year has 365 or 366. Adding one month to January 31 gives February 31, which does not exist. Java, .NET and the Temporal API of JavaScript then use the last day of the month, February 29 in 2024. Go AddDate, the JavaScript Date, C mktime and GNU date move the extra days into the next month and give March 2.
The contract add_to_date(year, month, day, years, months, days) returns the new date as YYYY-MM-DD with this rule:
- Add
years * 12 + monthsmonths at once. Keep the day. If the day is after the last day of the new month, use the last day. - Then add the days.
The order is part of the rule. One year and then one month from 2024-02-29 gives 2025-02-28 and then 2025-03-28. Thirteen months at once gives 2025-03-29.
Solutions
Each solution keeps the date in a type with no time zone, or in UTC. A date in local time can move by one hour on a day with a change of daylight saving time (see the pitfalls).
- Python.
date + timedelta(days=n)adds days. The standard library has no month arithmetic, so the solution computes the new year and month from a count of months and usescalendar.monthrange(year, month)[1]to get the last day of the month. - JavaScript.
Datehas no type for a date alone, so the solution uses the UTC methods.setUTCFullYear(year, monthIndex, day)accepts a day or a month out of range and moves into the next months. Day 0 of a month is the last day of the month before. The solution computes the last day this way and limits the day to it. Where the Temporal API is available,Temporal.PlainDatehasadd({ months: 1 }), and its defaultoverflow: 'constrain'uses the last day of the month. - TypeScript. The same code as JavaScript, with the type
number. - Java.
LocalDate.plusMonths(n)uses the last valid day of the month when the day is not valid, andplusDays(n)adds days. The solution callsplusMonths(years * 12L + months).plusDays(days).LocalDate.plus(Period.of(years, months, days))gives the same result. - C#.
DateOnly.AddMonths(n)andDateTime.AddMonths(n)use the last valid day of the resulting month. The documentation gives March 31 + 1 month = April 30.AddDays(n)adds days, andAddYears(n)adds years. - Go.
t.AddDate(years, months, days)adds all three at once and then normalizes the result, so one month after October 31 is December 1. The solution computes the new month itself, limits the day, and callsAddDate(0, 0, days)on atime.Timein UTC. - Rust. The standard library has no calendar date. The solution converts the date to a count of days and back with the
days_from_civilandcivil_from_daysalgorithms of Howard Hinnant. A crate such aschronoorjiffhas a date type with month arithmetic. - C.
mktimeaccepts fields out of range and normalizes them, so it moves January 31 + 1 month to March. It also reads the fields as local time. The solution uses the same day arithmetic as Rust, with a division that goes toward the past. - C++.
year_month_day + months{n}keeps the day, and the result is notok()for a day such as February 30. The solution then usesyear / month / last.sys_days{ymd} + days{n}adds days, andstd::format("{:%F}", d)writes the date. - Bash. GNU
date -d '2024-01-31 +1 month'moves the extra days into the next month. The GNU manual calls months and years "fuzzy units". The solution does the month arithmetic in the shell and adds the days to UTC seconds withdate -u -d @SECONDS +%F.
A date with no time zone gives the same result on each system:
import calendar
from datetime import date, timedelta
def add_months(start, months):
year, month0 = divmod(start.year * 12 + start.month - 1 + months, 12)
last = calendar.monthrange(year, month0 + 1)[1]
return start.replace(year=year, month=month0 + 1, day=min(start.day, last))
print(date(2024, 3, 10) + timedelta(days=30))
print(add_months(date(2024, 1, 31), 1))
print(add_months(date(2024, 2, 29), 12))
print(add_months(date(2024, 2, 29), 13))
2024-04-09
2024-02-29
2025-02-28
2025-03-29
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
nothing-to-add: 2024-02-29 with nothing added stays 2024-02-29.month-end-to-leap-february,month-end-to-short-februaryandmonth-end-to-30-day-month: January 31 + 1 month is February 29 in 2024 and February 28 in 2023, and March 31 + 1 month is April 30.back-from-month-endandback-to-leap-february: May 31 - 1 month is April 30, and 2024-03-31 - 1 month is 2024-02-29.leap-day-plus-one-yearandleap-day-plus-four-years: 2024-02-29 + 1 year is 2025-02-28, and + 4 years is 2028-02-29.year-and-month-at-onceandmonths-before-days: 2024-02-29 + 1 year 1 month is 2025-03-29, and 2024-01-31 + 1 month 1 day is 2024-03-01.month-into-next-year,thirteen-months-backandday-back-into-last-year: the month and the year change together.year-1900-is-not-leapandyear-2100-is-not-leap: 1900-02-28 + 1 day is 1900-03-01, and 2096-02-29 + 4 years is 2100-02-28.many-days,many-days-backandmany-months: 1970-01-01 + 2932896 days is 9999-12-31, and the other two cases go from one end of the years 1 to 9999 to the other.
Pitfalls
- Normalization moves the day into the next month. Go
AddDate,setUTCMonthin JavaScript, Cmktimeand GNUdateaccept February 31 and make it March 2 or 3:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
jan31 := time.Date(2024, time.January, 31, 0, 0, 0, 0, time.UTC)
oct31 := time.Date(2024, time.October, 31, 0, 0, 0, 0, time.UTC)
fmt.Println(jan31.AddDate(0, 1, 0).Format(time.DateOnly))
fmt.Println(oct31.AddDate(0, 1, 0).Format(time.DateOnly))
}
2024-03-02
2024-12-01
This code runs but gives a wrong answer on purpose.
date -u -d '2024-01-31 +1 month' +%F
date -u -d '2022-12-31 -1 month' +%F
2024-03-02
2022-12-01
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <time.h>
int main(void) {
struct tm tm = {0};
tm.tm_year = 2024 - 1900;
tm.tm_mon = 0; // January
tm.tm_mday = 31;
tm.tm_hour = 12;
tm.tm_isdst = -1;
tm.tm_mon += 1; // February 31
mktime(&tm);
printf("%04d-%02d-%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
}
2024-03-02
The libraries that limit the day give the last day of the month:
var march31 = new DateOnly(2024, 3, 31);
Console.WriteLine(march31.AddMonths(1).ToString("yyyy'-'MM'-'dd"));
Console.WriteLine(march31.AddMonths(-1).ToString("yyyy'-'MM'-'dd"));
Console.WriteLine(new DateOnly(2024, 1, 31).AddMonths(1).ToString("yyyy'-'MM'-'dd"));
2024-04-30
2024-02-29
2024-02-29
- Adding in steps gives a different date. Each step limits the day again. A year and then a month from a leap day loses one day. A month and then a month back does not return to the start date:
This code runs but gives a wrong answer on purpose.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate leapDay = LocalDate.of(2024, 2, 29);
System.out.println(leapDay.plusYears(1).plusMonths(1));
System.out.println(leapDay.plusMonths(13));
LocalDate jan31 = LocalDate.of(2024, 1, 31);
System.out.println(jan31.plusMonths(1).minusMonths(1));
}
}
2025-03-28
2025-03-29
2024-01-29
- A day is not always 24 hours. In a time zone with daylight saving time, the day of the change has 23 or 25 hours. In New York, the clocks went from 02:00 to 03:00 on 2024-03-10. Java
ZonedDateTime.plusDaysadds days to the local date and time, andplusHoursadds a duration:
This code runs but gives a wrong answer on purpose.
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime noon = ZonedDateTime.of(2024, 3, 9, 12, 0, 0, 0, ZoneId.of("America/New_York"));
System.out.println(noon.plusDays(1));
System.out.println(noon.plusHours(24));
}
}
2024-03-10T12:00-04:00[America/New_York]
2024-03-10T13:00-04:00[America/New_York]
In JavaScript, a number of milliseconds added to a local Date is a duration, and setDate changes the local date:
This code runs but gives a wrong answer on purpose.
process.env.TZ = "America/New_York";
const midnight = new Date(2024, 2, 10);
const plusMillis = new Date(midnight.getTime() + 24 * 60 * 60 * 1000);
const plusDate = new Date(midnight);
plusDate.setDate(plusDate.getDate() + 1);
console.log(plusMillis.getDate(), plusMillis.getHours());
console.log(plusDate.getDate(), plusDate.getHours());
11 1
11 0
Python adds a timedelta to the date and time on the clock, with no time zone adjustments. The result is one day later on the clock but only 23 hours later:
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
noon = datetime(2024, 3, 9, 12, 0, tzinfo=ZoneInfo("America/New_York"))
later = noon + timedelta(days=1)
print(later.isoformat())
print(later.astimezone(timezone.utc) - noon.astimezone(timezone.utc))
2024-03-10T12:00:00-04:00
23:00:00
To add days to a date, use a date type with no time zone, or do the arithmetic in UTC.
Related tasks
- Compute the difference of two dates: the number of days or months between two dates.
- Find the day of the week: the weekday of the result.
- Check for a leap year: the rule behind February 29.
- Convert between time zones: move an instant to another zone.
- Get a Unix timestamp: a date as seconds since 1970.
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/add-days-to-a-date/.
import calendar
from datetime import date, timedelta
def add_months(start: date, months: int) -> date:
"""Add months to a date. A day after the end of the new month becomes its last day."""
total = start.year * 12 + (start.month - 1) + months
year, month0 = divmod(total, 12)
last = calendar.monthrange(year, month0 + 1)[1]
return start.replace(year=year, month=month0 + 1, day=min(start.day, last))
def add_to_date(year: int, month: int, day: int, years: int, months: int, days: int) -> str:
"""Add years and months at once, then days, and return the date as YYYY-MM-DD."""
moved = add_months(date(year, month, day), years * 12 + months)
return (moved + timedelta(days=days)).isoformat()
test_add.py 48 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/add-days-to-a-date/.
from datetime import date
import pytest
from add import add_months, add_to_date
CASES = [
("one-day", (2024, 3, 10, 0, 0, 1), "2024-03-11"),
("one-month", (2024, 1, 15, 0, 1, 0), "2024-02-15"),
("one-year", (2023, 6, 1, 1, 0, 0), "2024-06-01"),
("day-into-next-year", (2023, 12, 31, 0, 0, 1), "2024-01-01"),
("nothing-to-add", (2024, 2, 29, 0, 0, 0), "2024-02-29"),
("month-end-to-leap-february", (2024, 1, 31, 0, 1, 0), "2024-02-29"),
("month-end-to-short-february", (2023, 1, 31, 0, 1, 0), "2023-02-28"),
("month-end-to-30-day-month", (2024, 3, 31, 0, 1, 0), "2024-04-30"),
("back-from-month-end", (2024, 5, 31, 0, -1, 0), "2024-04-30"),
("back-to-leap-february", (2024, 3, 31, 0, -1, 0), "2024-02-29"),
("leap-day-plus-one-year", (2024, 2, 29, 1, 0, 0), "2025-02-28"),
("leap-day-plus-four-years", (2024, 2, 29, 4, 0, 0), "2028-02-29"),
("year-and-month-at-once", (2024, 2, 29, 1, 1, 0), "2025-03-29"),
("months-before-days", (2024, 1, 31, 0, 1, 1), "2024-03-01"),
("month-into-next-year", (2023, 12, 15, 0, 1, 0), "2024-01-15"),
("thirteen-months-back", (2024, 1, 15, 0, -13, 0), "2022-12-15"),
("day-back-into-last-year", (2024, 1, 1, 0, 0, -1), "2023-12-31"),
("year-1900-is-not-leap", (1900, 2, 28, 0, 0, 1), "1900-03-01"),
("year-2100-is-not-leap", (2096, 2, 29, 4, 0, 0), "2100-02-28"),
("many-days", (1970, 1, 1, 0, 0, 2932896), "9999-12-31"),
("many-days-back", (9999, 12, 31, 0, 0, -3652058), "0001-01-01"),
("many-months", (1, 1, 31, 0, 119987, 0), "9999-12-31"),
]
@pytest.mark.parametrize(("name", "fields", "want"), CASES, ids=[c[0] for c in CASES])
def test_add_to_date(name, fields, want):
assert add_to_date(*fields) == want
def test_year_then_month_is_not_thirteen_months():
leap_day = date(2024, 2, 29)
assert add_months(add_months(leap_day, 12), 1) == date(2025, 3, 28)
assert add_months(leap_day, 13) == date(2025, 3, 29)
def test_a_month_and_back_can_lose_days():
assert add_months(add_months(date(2024, 1, 31), 1), -1) == date(2024, 1, 29)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
#pragma once
#include <chrono>
#include <format>
#include <string>
// Adds years and months at once, then days, and returns the date as
// YYYY-MM-DD. A day after the end of the new month becomes its last day.
inline std::string add_to_date(int year, int month, int day, int n_years, int n_months, int n_days) {
namespace chr = std::chrono;
const chr::year_month_day start{chr::year{year}, chr::month{static_cast<unsigned>(month)},
chr::day{static_cast<unsigned>(day)}};
// Adding months keeps the day. The result is not ok() for a day such as February 30.
chr::year_month_day moved = start + chr::months{n_years * 12 + n_months};
if (!moved.ok()) {
moved = moved.year() / moved.month() / chr::last;
}
const chr::sys_days result = chr::sys_days{moved} + chr::days{n_days};
return std::format("{:%F}", result);
}
test_add.cpp 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
#include <chrono>
#include <cstdio>
#include <string>
#include "add.hpp"
namespace {
struct test_case {
const char* name;
int year, month, day, years, months, days;
const char* want;
};
const test_case cases[] = {
{"one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11"},
{"one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15"},
{"one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01"},
{"day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01"},
{"nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29"},
{"month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29"},
{"month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28"},
{"month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30"},
{"back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30"},
{"back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29"},
{"leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28"},
{"leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29"},
{"year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29"},
{"months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01"},
{"month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15"},
{"thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15"},
{"day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31"},
{"year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01"},
{"year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28"},
{"many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31"},
{"many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01"},
{"many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31"},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const std::string got = add_to_date(c.year, c.month, c.day, c.years, c.months, c.days);
if (got != c.want) {
std::printf("FAIL %s: got %s, want %s\n", c.name, got.c_str(), c.want);
++failures;
}
}
using namespace std::chrono;
const year_month_day not_ok = 2024y / January / 31d + months{1};
if (not_ok.ok()) {
std::printf("FAIL 2024-01-31 + 1 month should not be ok()\n");
++failures;
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
import java.time.LocalDate;
public final class AddDate {
private AddDate() {}
/**
* Adds years and months at once, then days, and returns the date as YYYY-MM-DD.
* plusMonths uses the last day of the new month when the day is not valid in it.
*/
public static String addToDate(int year, int month, int day, int years, int months, int days) {
return LocalDate.of(year, month, day)
.plusMonths(years * 12L + months)
.plusDays(days)
.toString();
}
}
AddDateTest.java 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
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 AddDateTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11"),
Arguments.of("one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15"),
Arguments.of("one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01"),
Arguments.of("day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01"),
Arguments.of("nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29"),
Arguments.of("month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29"),
Arguments.of("month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28"),
Arguments.of("month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30"),
Arguments.of("back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30"),
Arguments.of("back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29"),
Arguments.of("leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28"),
Arguments.of("leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29"),
Arguments.of("year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29"),
Arguments.of("months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01"),
Arguments.of("month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15"),
Arguments.of("thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15"),
Arguments.of("day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31"),
Arguments.of("year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01"),
Arguments.of("year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28"),
Arguments.of("many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31"),
Arguments.of("many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01"),
Arguments.of("many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31")
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void addToDate(String name, int year, int month, int day, int years, int months, int days, String want) {
assertEquals(want, AddDate.addToDate(year, month, day, years, months, days));
}
@Test
void plusYearsThenPlusMonthsIsNotPlusThirteenMonths() {
LocalDate leapDay = LocalDate.of(2024, 2, 29);
assertEquals(LocalDate.of(2025, 3, 28), leapDay.plusYears(1).plusMonths(1));
assertEquals(LocalDate.of(2025, 3, 29), leapDay.plusMonths(13));
assertEquals(LocalDate.of(2025, 3, 29), leapDay.plus(Period.of(1, 1, 0)));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
#include "add.h"
#include <stdint.h>
#include <stdio.h>
static int is_leap(int64_t year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
static int64_t days_in_month(int64_t year, int64_t month) {
static const int64_t length[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return month == 2 && is_leap(year) ? 29 : length[month - 1];
}
// Division toward the past. The / of C goes toward zero.
static int64_t floor_div(int64_t a, int64_t b) {
int64_t q = a / b;
return (a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;
}
// The days from 1970-01-01 to a date, and back (Howard Hinnant).
static int64_t days_from_civil(int64_t year, int64_t month, int64_t day) {
int64_t y = month <= 2 ? year - 1 : year;
int64_t era = floor_div(y, 400);
int64_t yoe = y - era * 400;
int64_t mp = (month + 9) % 12;
int64_t doy = (153 * mp + 2) / 5 + day - 1;
int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
static void civil_from_days(int64_t days, int64_t *year, int64_t *month, int64_t *day) {
int64_t z = days + 719468;
int64_t era = floor_div(z, 146097);
int64_t doe = z - era * 146097;
int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
int64_t mp = (5 * doy + 2) / 153;
*day = doy - (153 * mp + 2) / 5 + 1;
*month = mp < 10 ? mp + 3 : mp - 9;
*year = yoe + era * 400 + (*month <= 2);
}
int add_to_date(int year, int month, int day, int years, int months, int days, char *out, size_t size) {
int64_t total = (int64_t)year * 12 + (month - 1) + (int64_t)years * 12 + months;
int64_t new_year = floor_div(total, 12);
int64_t new_month = total - new_year * 12 + 1;
int64_t last = days_in_month(new_year, new_month);
int64_t new_day = day < last ? day : last;
int64_t y, m, d;
civil_from_days(days_from_civil(new_year, new_month, new_day) + days, &y, &m, &d);
int n = snprintf(out, size, "%04d-%02d-%02d", (int)y, (int)m, (int)d);
return (n < 0 || (size_t)n >= size) ? -1 : 0;
}
add.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
#ifndef ADD_TO_DATE_H
#define ADD_TO_DATE_H
#include <stddef.h>
// Adds years and months at once, then days, and writes the date as
// YYYY-MM-DD to out. A day after the end of the new month becomes its last
// day. Returns 0, or -1 if out is too small.
int add_to_date(int year, int month, int day, int years, int months, int days, char *out, size_t size);
#endif
test_add.c 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
#include "add.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
int year, month, day, years, months, days;
const char *want;
};
static const struct test_case cases[] = {
{"one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11"},
{"one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15"},
{"one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01"},
{"day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01"},
{"nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29"},
{"month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29"},
{"month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28"},
{"month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30"},
{"back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30"},
{"back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29"},
{"leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28"},
{"leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29"},
{"year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29"},
{"months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01"},
{"month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15"},
{"thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15"},
{"day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31"},
{"year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01"},
{"year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28"},
{"many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31"},
{"many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01"},
{"many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31"},
};
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];
char got[16];
int rc = add_to_date(c->year, c->month, c->day, c->years, c->months, c->days, got, sizeof got);
if (rc != 0 || strcmp(got, c->want) != 0) {
printf("FAIL %s: got %s, want %s\n", c->name, got, c->want);
failures++;
}
}
char small[4];
if (add_to_date(2024, 1, 1, 0, 0, 0, small, sizeof small) != -1) {
printf("FAIL small buffer\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
using System.Globalization;
public static class AddDate
{
/// <summary>
/// Adds years and months at once, then days, and returns the date as YYYY-MM-DD.
/// AddMonths uses the last day of the new month when the day is not valid in it.
/// </summary>
public static string AddToDate(int year, int month, int day, int years, int months, int days) =>
new DateOnly(year, month, day)
.AddMonths(years * 12 + months)
.AddDays(days)
.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture);
}
AddDateTests.cs 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
using Xunit;
public sealed class AddDateTests
{
public static TheoryData<string, int, int, int, int, int, int, string> Cases => new()
{
{ "one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11" },
{ "one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15" },
{ "one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01" },
{ "day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01" },
{ "nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29" },
{ "month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29" },
{ "month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28" },
{ "month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30" },
{ "back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30" },
{ "back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29" },
{ "leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28" },
{ "leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29" },
{ "year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29" },
{ "months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01" },
{ "month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15" },
{ "thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15" },
{ "day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31" },
{ "year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01" },
{ "year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28" },
{ "many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31" },
{ "many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01" },
{ "many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31" },
};
[Theory]
[MemberData(nameof(Cases))]
public void AddToDate(string name, int year, int month, int day, int years, int months, int days, string want)
{
Assert.NotNull(name);
Assert.Equal(want, AddDate.AddToDate(year, month, day, years, months, days));
}
[Fact]
public void AddYearsThenAddMonthsIsNotThirteenMonths()
{
var leapDay = new DateOnly(2024, 2, 29);
Assert.Equal(new DateOnly(2025, 3, 28), leapDay.AddYears(1).AddMonths(1));
Assert.Equal(new DateOnly(2025, 3, 29), leapDay.AddMonths(13));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
/** Returns the number of days in a month (1 to 12) of a year. */
export function daysInMonth(year, month) {
const date = new Date(0);
// Day 0 of the next month is the last day of this month.
date.setUTCFullYear(year, month, 0);
return date.getUTCDate();
}
/**
* Adds years and months at once, then days, and returns the date as YYYY-MM-DD.
* A day after the end of the new month becomes its last day.
* The code uses the UTC methods of Date, so the local time zone has no effect.
*/
export function addToDate(year, month, day, years, months, days) {
const total = year * 12 + (month - 1) + years * 12 + months;
const newYear = Math.floor(total / 12);
const newMonth = total - newYear * 12 + 1;
const newDay = Math.min(day, daysInMonth(newYear, newMonth));
const date = new Date(0);
// setUTCFullYear accepts a day after the end of the month and moves to the next months.
date.setUTCFullYear(newYear, newMonth - 1, newDay + days);
return date.toISOString().slice(0, 10);
}
add.test.js 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { addToDate, daysInMonth } from "./add.js";
const cases = [
["one-day", [2024, 3, 10, 0, 0, 1], "2024-03-11"],
["one-month", [2024, 1, 15, 0, 1, 0], "2024-02-15"],
["one-year", [2023, 6, 1, 1, 0, 0], "2024-06-01"],
["day-into-next-year", [2023, 12, 31, 0, 0, 1], "2024-01-01"],
["nothing-to-add", [2024, 2, 29, 0, 0, 0], "2024-02-29"],
["month-end-to-leap-february", [2024, 1, 31, 0, 1, 0], "2024-02-29"],
["month-end-to-short-february", [2023, 1, 31, 0, 1, 0], "2023-02-28"],
["month-end-to-30-day-month", [2024, 3, 31, 0, 1, 0], "2024-04-30"],
["back-from-month-end", [2024, 5, 31, 0, -1, 0], "2024-04-30"],
["back-to-leap-february", [2024, 3, 31, 0, -1, 0], "2024-02-29"],
["leap-day-plus-one-year", [2024, 2, 29, 1, 0, 0], "2025-02-28"],
["leap-day-plus-four-years", [2024, 2, 29, 4, 0, 0], "2028-02-29"],
["year-and-month-at-once", [2024, 2, 29, 1, 1, 0], "2025-03-29"],
["months-before-days", [2024, 1, 31, 0, 1, 1], "2024-03-01"],
["month-into-next-year", [2023, 12, 15, 0, 1, 0], "2024-01-15"],
["thirteen-months-back", [2024, 1, 15, 0, -13, 0], "2022-12-15"],
["day-back-into-last-year", [2024, 1, 1, 0, 0, -1], "2023-12-31"],
["year-1900-is-not-leap", [1900, 2, 28, 0, 0, 1], "1900-03-01"],
["year-2100-is-not-leap", [2096, 2, 29, 4, 0, 0], "2100-02-28"],
["many-days", [1970, 1, 1, 0, 0, 2932896], "9999-12-31"],
["many-days-back", [9999, 12, 31, 0, 0, -3652058], "0001-01-01"],
["many-months", [1, 1, 31, 0, 119987, 0], "9999-12-31"],
];
for (const [name, fields, want] of cases) {
test(name, () => {
const [year, month, day, years, months, days] = fields;
assert.equal(addToDate(year, month, day, years, months, days), want);
});
}
test("daysInMonth", () => {
assert.equal(daysInMonth(2024, 2), 29);
assert.equal(daysInMonth(1900, 2), 28);
assert.equal(daysInMonth(2024, 12), 31);
});
test("setUTCMonth alone moves past the end of the month", () => {
const date = new Date(Date.UTC(2024, 0, 31));
date.setUTCMonth(1);
assert.equal(date.toISOString().slice(0, 10), "2024-03-02");
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
/** Returns the number of days in a month (1 to 12) of a year. */
export function daysInMonth(year: number, month: number): number {
const date = new Date(0);
// Day 0 of the next month is the last day of this month.
date.setUTCFullYear(year, month, 0);
return date.getUTCDate();
}
/**
* Adds years and months at once, then days, and returns the date as YYYY-MM-DD.
* A day after the end of the new month becomes its last day.
* The code uses the UTC methods of Date, so the local time zone has no effect.
*/
export function addToDate(year: number, month: number, day: number, years: number, months: number, days: number): string {
const total = year * 12 + (month - 1) + years * 12 + months;
const newYear = Math.floor(total / 12);
const newMonth = total - newYear * 12 + 1;
const newDay = Math.min(day, daysInMonth(newYear, newMonth));
const date = new Date(0);
// setUTCFullYear accepts a day after the end of the month and moves to the next months.
date.setUTCFullYear(newYear, newMonth - 1, newDay + days);
return date.toISOString().slice(0, 10);
}
add.test.ts 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { addToDate, daysInMonth } from "./add.ts";
const cases: [string, [number, number, number, number, number, number], string][] = [
["one-day", [2024, 3, 10, 0, 0, 1], "2024-03-11"],
["one-month", [2024, 1, 15, 0, 1, 0], "2024-02-15"],
["one-year", [2023, 6, 1, 1, 0, 0], "2024-06-01"],
["day-into-next-year", [2023, 12, 31, 0, 0, 1], "2024-01-01"],
["nothing-to-add", [2024, 2, 29, 0, 0, 0], "2024-02-29"],
["month-end-to-leap-february", [2024, 1, 31, 0, 1, 0], "2024-02-29"],
["month-end-to-short-february", [2023, 1, 31, 0, 1, 0], "2023-02-28"],
["month-end-to-30-day-month", [2024, 3, 31, 0, 1, 0], "2024-04-30"],
["back-from-month-end", [2024, 5, 31, 0, -1, 0], "2024-04-30"],
["back-to-leap-february", [2024, 3, 31, 0, -1, 0], "2024-02-29"],
["leap-day-plus-one-year", [2024, 2, 29, 1, 0, 0], "2025-02-28"],
["leap-day-plus-four-years", [2024, 2, 29, 4, 0, 0], "2028-02-29"],
["year-and-month-at-once", [2024, 2, 29, 1, 1, 0], "2025-03-29"],
["months-before-days", [2024, 1, 31, 0, 1, 1], "2024-03-01"],
["month-into-next-year", [2023, 12, 15, 0, 1, 0], "2024-01-15"],
["thirteen-months-back", [2024, 1, 15, 0, -13, 0], "2022-12-15"],
["day-back-into-last-year", [2024, 1, 1, 0, 0, -1], "2023-12-31"],
["year-1900-is-not-leap", [1900, 2, 28, 0, 0, 1], "1900-03-01"],
["year-2100-is-not-leap", [2096, 2, 29, 4, 0, 0], "2100-02-28"],
["many-days", [1970, 1, 1, 0, 0, 2932896], "9999-12-31"],
["many-days-back", [9999, 12, 31, 0, 0, -3652058], "0001-01-01"],
["many-months", [1, 1, 31, 0, 119987, 0], "9999-12-31"],
];
for (const [name, fields, want] of cases) {
test(name, () => {
const [year, month, day, years, months, days] = fields;
assert.equal(addToDate(year, month, day, years, months, days), want);
});
}
test("daysInMonth", () => {
assert.equal(daysInMonth(2024, 2), 29);
assert.equal(daysInMonth(1900, 2), 28);
assert.equal(daysInMonth(2024, 12), 31);
});
test("setUTCMonth alone moves past the end of the month", () => {
const date = new Date(Date.UTC(2024, 0, 31));
date.setUTCMonth(1);
assert.equal(date.toISOString().slice(0, 10), "2024-03-02");
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
package add
import "time"
// DaysIn returns the number of days in a month of a year.
func DaysIn(year int, month time.Month) int {
// Day 0 of the next month is the last day of this month.
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
// AddToDate adds years and months at once, then days, and returns the date as
// YYYY-MM-DD. A day after the end of the new month becomes its last day.
// AddDate alone would move such a day into the next month.
func AddToDate(year, month, day, years, months, days int) string {
total := year*12 + (month - 1) + years*12 + months
newYear, newMonth := total/12, time.Month(total%12+1)
newDay := min(day, DaysIn(newYear, newMonth))
moved := time.Date(newYear, newMonth, newDay, 0, 0, 0, 0, time.UTC)
return moved.AddDate(0, 0, days).Format(time.DateOnly)
}
add_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
package add
import (
"testing"
"time"
)
var cases = []struct {
name string
year, month, day, years, months, days int
want string
}{
{"one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11"},
{"one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15"},
{"one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01"},
{"day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01"},
{"nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29"},
{"month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29"},
{"month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28"},
{"month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30"},
{"back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30"},
{"back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29"},
{"leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28"},
{"leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29"},
{"year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29"},
{"months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01"},
{"month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15"},
{"thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15"},
{"day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31"},
{"year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01"},
{"year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28"},
{"many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31"},
{"many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01"},
{"many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31"},
}
func TestAddToDate(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := AddToDate(c.year, c.month, c.day, c.years, c.months, c.days); got != c.want {
t.Fatalf("got %s, want %s", got, c.want)
}
})
}
}
func TestAddDateMovesPastTheEndOfTheMonth(t *testing.T) {
jan31 := time.Date(2024, time.January, 31, 0, 0, 0, 0, time.UTC)
if got := jan31.AddDate(0, 1, 0).Format(time.DateOnly); got != "2024-03-02" {
t.Fatalf("got %s", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
/// Returns true for a leap year of the Gregorian calendar.
pub fn is_leap(year: i64) -> bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
/// Returns the number of days in a month (1 to 12) of a year.
pub fn days_in_month(year: i64, month: i64) -> i64 {
match month {
2 if is_leap(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
/// Returns the number of days from 1970-01-01 to a date (Howard Hinnant).
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 date of a number of days from 1970-01-01 (Howard Hinnant).
pub fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
/// Adds years and months at once, then days, and returns the date as
/// YYYY-MM-DD. A day after the end of the new month becomes its last day.
pub fn add_to_date(year: i64, month: i64, day: i64, years: i64, months: i64, days: i64) -> String {
let total = year * 12 + (month - 1) + years * 12 + months;
let new_year = total.div_euclid(12);
let new_month = total.rem_euclid(12) + 1;
let new_day = day.min(days_in_month(new_year, new_month));
let (y, m, d) = civil_from_days(days_from_civil(new_year, new_month, new_day) + days);
format!("{y:04}-{m:02}-{d:02}")
}
tests/add_test.rs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-days-to-a-date/.
use algo_add_days_to_a_date::{add_to_date, civil_from_days, days_from_civil, days_in_month};
#[allow(clippy::type_complexity)]
const CASES: &[(&str, i64, i64, i64, i64, i64, i64, &str)] = &[
("one-day", 2024, 3, 10, 0, 0, 1, "2024-03-11"),
("one-month", 2024, 1, 15, 0, 1, 0, "2024-02-15"),
("one-year", 2023, 6, 1, 1, 0, 0, "2024-06-01"),
("day-into-next-year", 2023, 12, 31, 0, 0, 1, "2024-01-01"),
("nothing-to-add", 2024, 2, 29, 0, 0, 0, "2024-02-29"),
("month-end-to-leap-february", 2024, 1, 31, 0, 1, 0, "2024-02-29"),
("month-end-to-short-february", 2023, 1, 31, 0, 1, 0, "2023-02-28"),
("month-end-to-30-day-month", 2024, 3, 31, 0, 1, 0, "2024-04-30"),
("back-from-month-end", 2024, 5, 31, 0, -1, 0, "2024-04-30"),
("back-to-leap-february", 2024, 3, 31, 0, -1, 0, "2024-02-29"),
("leap-day-plus-one-year", 2024, 2, 29, 1, 0, 0, "2025-02-28"),
("leap-day-plus-four-years", 2024, 2, 29, 4, 0, 0, "2028-02-29"),
("year-and-month-at-once", 2024, 2, 29, 1, 1, 0, "2025-03-29"),
("months-before-days", 2024, 1, 31, 0, 1, 1, "2024-03-01"),
("month-into-next-year", 2023, 12, 15, 0, 1, 0, "2024-01-15"),
("thirteen-months-back", 2024, 1, 15, 0, -13, 0, "2022-12-15"),
("day-back-into-last-year", 2024, 1, 1, 0, 0, -1, "2023-12-31"),
("year-1900-is-not-leap", 1900, 2, 28, 0, 0, 1, "1900-03-01"),
("year-2100-is-not-leap", 2096, 2, 29, 4, 0, 0, "2100-02-28"),
("many-days", 1970, 1, 1, 0, 0, 2932896, "9999-12-31"),
("many-days-back", 9999, 12, 31, 0, 0, -3652058, "0001-01-01"),
("many-months", 1, 1, 31, 0, 119987, 0, "9999-12-31"),
];
#[test]
fn cases() {
for &(name, year, month, day, years, months, days, want) in CASES {
assert_eq!(add_to_date(year, month, day, years, months, days), want, "{name}");
}
}
#[test]
fn round_trip_of_days() {
for days in [-719_162, -1, 0, 1, 19_782, 2_932_896] {
let (y, m, d) = civil_from_days(days);
assert_eq!(days_from_civil(y, m, d), days);
}
}
#[test]
fn month_lengths() {
assert_eq!(days_in_month(2024, 2), 29);
assert_eq!(days_in_month(1900, 2), 28);
assert_eq!(days_in_month(2000, 2), 29);
assert_eq!(days_in_month(2024, 4), 30);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/add-days-to-a-date/.
# days_in_month YEAR MONTH prints the number of days in the month.
days_in_month() {
local year=$1 month=$2
case $month in
2)
if (( year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) )); then echo 29; else echo 28; fi
;;
4 | 6 | 9 | 11) echo 30 ;;
*) echo 31 ;;
esac
}
# add_to_date YEAR MONTH DAY YEARS MONTHS DAYS
# Adds years and months at once, then days, and prints the date as YYYY-MM-DD.
# A day after the end of the new month becomes its last day. The months use
# shell arithmetic, because GNU date moves such a day into the next month.
# The days use UTC seconds, so no time zone change can move the result.
add_to_date() {
local year=$1 month=$2 day=$3 years=$4 months=$5 days=$6
local total=$(( year * 12 + month - 1 + years * 12 + months ))
local new_year=$(( total / 12 )) new_month=$(( total % 12 + 1 ))
local last
last=$(days_in_month "$new_year" "$new_month")
(( day > last )) && day=$last
local start
start=$(date -u -d "$(printf '%04d-%02d-%02d' "$new_year" "$new_month" "$day")" +%s) || return 1
date -u -d "@$(( start + days * 86400 ))" +%F
}
test_add.bats 42 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/add-days-to-a-date/.
setup() {
source "$BATS_TEST_DIRNAME/add.sh"
}
@test "one-day" { run add_to_date 2024 3 10 0 0 1; [ "$status" -eq 0 ]; [ "$output" = "2024-03-11" ]; }
@test "one-month" { run add_to_date 2024 1 15 0 1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-02-15" ]; }
@test "one-year" { run add_to_date 2023 6 1 1 0 0; [ "$status" -eq 0 ]; [ "$output" = "2024-06-01" ]; }
@test "day-into-next-year" { run add_to_date 2023 12 31 0 0 1; [ "$status" -eq 0 ]; [ "$output" = "2024-01-01" ]; }
@test "nothing-to-add" { run add_to_date 2024 2 29 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "2024-02-29" ]; }
@test "month-end-to-leap-february" { run add_to_date 2024 1 31 0 1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-02-29" ]; }
@test "month-end-to-short-february" { run add_to_date 2023 1 31 0 1 0; [ "$status" -eq 0 ]; [ "$output" = "2023-02-28" ]; }
@test "month-end-to-30-day-month" { run add_to_date 2024 3 31 0 1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-04-30" ]; }
@test "back-from-month-end" { run add_to_date 2024 5 31 0 -1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-04-30" ]; }
@test "back-to-leap-february" { run add_to_date 2024 3 31 0 -1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-02-29" ]; }
@test "leap-day-plus-one-year" { run add_to_date 2024 2 29 1 0 0; [ "$status" -eq 0 ]; [ "$output" = "2025-02-28" ]; }
@test "leap-day-plus-four-years" { run add_to_date 2024 2 29 4 0 0; [ "$status" -eq 0 ]; [ "$output" = "2028-02-29" ]; }
@test "year-and-month-at-once" { run add_to_date 2024 2 29 1 1 0; [ "$status" -eq 0 ]; [ "$output" = "2025-03-29" ]; }
@test "months-before-days" { run add_to_date 2024 1 31 0 1 1; [ "$status" -eq 0 ]; [ "$output" = "2024-03-01" ]; }
@test "month-into-next-year" { run add_to_date 2023 12 15 0 1 0; [ "$status" -eq 0 ]; [ "$output" = "2024-01-15" ]; }
@test "thirteen-months-back" { run add_to_date 2024 1 15 0 -13 0; [ "$status" -eq 0 ]; [ "$output" = "2022-12-15" ]; }
@test "day-back-into-last-year" { run add_to_date 2024 1 1 0 0 -1; [ "$status" -eq 0 ]; [ "$output" = "2023-12-31" ]; }
@test "year-1900-is-not-leap" { run add_to_date 1900 2 28 0 0 1; [ "$status" -eq 0 ]; [ "$output" = "1900-03-01" ]; }
@test "year-2100-is-not-leap" { run add_to_date 2096 2 29 4 0 0; [ "$status" -eq 0 ]; [ "$output" = "2100-02-28" ]; }
@test "many-days" { run add_to_date 1970 1 1 0 0 2932896; [ "$status" -eq 0 ]; [ "$output" = "9999-12-31" ]; }
@test "many-days-back" { run add_to_date 9999 12 31 0 0 -3652058; [ "$status" -eq 0 ]; [ "$output" = "0001-01-01" ]; }
@test "many-months" { run add_to_date 1 1 31 0 119987 0; [ "$status" -eq 0 ]; [ "$output" = "9999-12-31" ]; }
@test "days_in_month" {
[ "$(days_in_month 2024 2)" = 29 ]
[ "$(days_in_month 1900 2)" = 28 ]
[ "$(days_in_month 2000 2)" = 29 ]
[ "$(days_in_month 2024 4)" = 30 ]
}
@test "GNU date alone moves past the end of the month" {
run date -u -d '2024-01-31 +1 month' +%F
[ "$output" = "2024-03-02" ]
}
References
- The Python Standard Library, datetime, timedelta objects; Supported operations of datetime (datetime2 = datetime1 + timedelta)
- The Python Standard Library, calendar, calendar.monthrange
- MDN Web Docs, Date.prototype.setUTCMonth(), Description
- MDN Web Docs, Date.prototype.setUTCFullYear(), Description
- TC39 Temporal proposal, Temporal.PlainDate, date.add(duration, options)
- Java SE 25 API, java.time.LocalDate, plusMonths(long); plusYears(long); plusDays(long)
- Java SE 25 API, java.time.ZonedDateTime, plusDays(long); plusHours(long)
- .NET API reference, DateTime.AddMonths, Remarks
- .NET API reference, DateOnly.AddMonths, Returns
- Go standard library, time, func (Time) AddDate; func Date
- cppreference.com, std::chrono::year_month_day::operator+=, operator-=, Notes; Example
- The Open Group Base Specifications Issue 8, mktime, DESCRIPTION
- GNU Coreutils manual, Relative items in date strings, the fuzz in units
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 8AE4TK Edit this page History Report an error Markdown