Age Calculator: Checking Age-Group Eligibility Against a League Cutoff Date (Python, Node, Browser)

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Age Calculator: Checking Age-Group Eligibility Against a League Cutoff Date (Python, Node, Browser)

去年八月,我被卷入了我们足球俱乐部的注册混乱中。联盟的规则很简单:U-12 意味着球员在 2026 年 8 月 1 日时仍为 11 岁。不是今天 11 岁,而是在截止日期当天 11 岁。前任协调员在截止日期前一周检查了年龄,目测了一下剩余人员就完事了。结果两个孩子被分到了错误的组别。其中一个出生于 2014 年 7 月 28 日的孩子,在审核名单时是 11 岁,但在截止日期当天就满 12 岁了。抗议被提出,分组被重做,协调员感到非常尴尬。我将检查过程重写为一个脚本,并将其保存在代码库中。名单现在保存在一个共享电子表格中,联盟以书面形式公布截止日期,整个验证过程现在只需 30 秒,在任何人签署任何文件之前运行。以下是实现相同目的的三种方法,从最可重复的方法到处理单个案例最快的方法。

Method 1: a small Python script

Python 3.11.1, standard library only. “Age at a date” is the same borrow logic as “age today”, just against a fixed cutoff: you start with the year difference and subtract one whenever the birthday falls after the date you’re measuring at. The only twist is that the “current date” is a parameter instead of date.today():

方法 1:小型 Python 脚本

Python 3.11.1,仅使用标准库。“某日期的年龄”与“今天年龄”的借位逻辑相同,只是针对一个固定的截止日期:你从年份差开始,每当生日落在测量日期之后时就减去一。唯一的不同之处在于,“当前日期”是一个参数,而不是 date.today():

# check_eligibility.py — Python 3.11.1, standard library only
import csv
from datetime import date

CUTOFF = date(2026, 8, 1)
MAX_AGE = 11 # U-12 = still 11 on cutoff day

def age_at(dob: date, at: date) -> int:
    years = at.year - dob.year
    if (at.month, at.day) < (dob.month, dob.day):
        years -= 1
    return years

with open("registrations.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        y, m, d = (int(p) for p in row["dob"].split("-"))
        age = age_at(date(y, m, d), CUTOFF)
        status = "OK" if age <= MAX_AGE else "NOT eligible"
        print(f"{row['player']}: born {row['dob']} -> {age} at cutoff, {status}")

The relevant slice of the real output: Lucas M.: born 2014-07-28 -> 12 at cutoff, NOT eligible Priya S.: born 2014-08-05 -> 11 at cutoff, OK

实际输出的相关片段: Lucas M.: born 2014-07-28 -> 12 at cutoff, NOT eligible Priya S.: born 2014-08-05 -> 11 at cutoff, OK

One subtlety: (at.month, at.day) < (dob.month, dob.day) compares tuples on purpose. My first version used dob.replace(year=at.year) and a player born 2000-02-29 blew up with ValueError: day is out of range for month, because Feb 29 doesn’t exist in 2026. Tuple comparison never builds an invalid date, so leap-day birthdays pass through. The datetime module docs have the details if you want them.

一个微妙之处在于:(at.month, at.day) < (dob.month, dob.day) 是特意比较元组的。我的第一个版本使用了 dob.replace(year=at.year),结果一个出生于 2000 年 2 月 29 日的球员导致了 ValueError: day is out of range for month,因为 2026 年没有 2 月 29 日。元组比较永远不会构建无效日期,因此闰日生日可以顺利通过。如果你需要详细信息,可以查阅 datetime 模块的文档。

Method 2: Node.js

The same logic in Node 22.13.1, no dependencies. I use this when the roster lands as a spreadsheet export and the rest of our tooling is already JavaScript:

方法 2:Node.js

在 Node 22.13.1 中使用相同的逻辑,无需依赖项。当名单以电子表格导出形式出现,且我们其余的工具链已经是 JavaScript 时,我会使用这种方法:

// check.mjs — Node 22.13.1, no dependencies
import { readFileSync } from "node:fs";

const cutoff = new Date(2026, 7, 1); // 0-indexed: 7 = August
const maxAge = 11;

function ageAt(dob, at) {
    let years = at.getFullYear() - dob.getFullYear();
    const beforeBirthday = at.getMonth() < dob.getMonth() || 
        (at.getMonth() === dob.getMonth() && at.getDate() < dob.getDate());
    if (beforeBirthday) years--;
    return years;
}

const rows = readFileSync("registrations.csv", "utf8").trim().split("\n").slice(1);
for (const row of rows) {
    const [player, dobStr] = row.split(",");
    const [y, m, d] = dobStr.split("-").map(Number);
    const age = ageAt(new Date(y, m - 1, d), cutoff);
    console.log(`${player}: born {dobStr} -> ${age} at cutoff`);
}

That m - 1 is doing load-bearing work. More on that in a second. For everything else the Date object can do to you, MDN’s Date reference is the page I keep open.

那个 m - 1 起到了关键作用。稍后我会详细说明。至于 Date 对象可能带来的其他问题,MDN 的 Date 参考页面是我常备的参考资料。

Method 3: the browser, for one-off cases

The script path earns its keep at roster scale. At registration-desk scale — one parent, one birth certificate, one disputed bracket — opening a terminal is theater. I open this browser-based age calculator, type the date of birth and the “as of” date, and read out years/months/days plus total days and hours. The years/months/days breakdown matters more than I expected: “eleven and a half” lands very differently than “eleven, turning twelve tomorrow” when you’re explaining a decision to a parent. It runs fully client-side, nothing is uploaded, which matters when the input is a child’s birth date. Two or three contested cases per season is exactly what a free online age calculator is for; 214 rows is what the script is for.

方法 3:浏览器,用于一次性案例

脚本路径在处理大规模名单时很有价值。但在注册台规模下——一位家长、一份出生证明、一个有争议的分组——打开终端就显得有些做作了。我打开这个基于浏览器的年龄计算器,输入出生日期和“截止”日期,然后读出年/月/日以及总天数和小时数。年/月/日的细分比我预期的更重要:当你向家长解释决定时,“十一岁半”和“十一岁,明天满十二岁”给人的感觉截然不同。它完全在客户端运行,没有任何内容被上传,这在输入是儿童出生日期时非常重要。每个赛季两三个有争议的案例正是免费在线年龄计算器的用武之地;而 214 行的数据才是脚本的用处。

Three traps I hit so you don’t have to

Trap 1: dateutil’s argument order. My favorite shortcut betrayed me once. I swapped the arguments, and the eligibility check silently passed for the one player it should have flagged: >>> from datetime import date >>> from dateutil.relativedelta import relativedelta >>> r = relativedelta(date(2014, 7, 20), date(2026, 8, 1)) >>> r relativedelta(years=-12, days=-12) >>> r.years > 11 False years=-12, no exception, no warning — and r.years > 11 is False, so a 12-year-old stayed in the U-12 list. relativedelta(cutoff, dob) is the correct order; the relativedelta docs define it as a subtraction, and the direction is on you.

我踩过的三个坑,希望你不用再踩

陷阱 1:dateutil 的参数顺序。 我最喜欢的快捷方式曾背叛过我一次。我交换了参数,结果资格检查对本应标记的一名球员静默通过了: >>> from datetime import date >>> from dateutil.relativedelta import relativedelta >>> r = relativedelta(date(2014, 7, 20), date(2026, 8, 1)) >>> r relativedelta(years=-12, days=-12) >>> r.years > 11 False years=-12,没有异常,没有警告——而且 r.years > 11 为 False,所以一个 12 岁的孩子留在了 U-12 名单中。relativedelta(cutoff, dob) 才是正确的顺序;relativedelta 文档将其定义为减法,方向由你自己决定。

Trap 2: JavaScript months start at zero. A colleague’s version built DOBs with new Date(2013, 8, 2) for an August 2 birthday. Watch what that actually constructs: > new Date(2013, 8, 2).toString() "Mon Sep 02 2013 00:00:00 GMT+0800 (China Standard Time)" September 2. In that case the age number happened to come out the same, because September 2 sits on the same side of the August 1 cutoff as August 2 does. That’s exactly what makes the bug nasty: the eligibility column looks right, nothing fails, and the wrong birthday just quietly travels into the league card. The parent caught it on paper. The fix is boring and non-negotiable: subtract one from any month you read out of a human-facing source, and print the parsed date back once so a human sees what the machine thinks.

陷阱 2:JavaScript 月份从零开始。 一位同事的版本在处理 8 月 2 日的生日时,使用了 new Date(2013, 8, 2) 来构建出生日期。看看这实际上构建了什么: > new Date(2013, 8, 2).toString() "Mon Sep 02 2013 00:00:00 GMT+0800 (China Standard Time)" 9 月 2 日。在这种情况下,年龄数字恰好算出来是一样的,因为 9 月 2 日和 8 月 2 日都在 8 月 1 日截止日期的同一侧。这正是这个 Bug 棘手的地方:资格列看起来是对的,没有任何报错,错误的生日就悄悄地进入了联盟卡片。家长在纸质文件上发现了它。修复方法很枯燥且不可商量:从面向人类的来源读取的任何月份都要减去一,并将解析后的日期打印出来,以便人类能看到机器认为的日期是什么。

Trap 3: unpadded dates in spreadsheets. Someone hand-edited our export and one cell said 2014-8-2. One cell, two failures. Python 3.11’s date.fromisoformat — friendlier since 3.11, but still strict about this — rejects it: ValueError: Invalid isoformat string: '2014-8-2' The string comparison didn’t catch it either, because ‘2014-8-2’ < ‘2014-08-01’ evaluates to False — ‘8’ sorts after ‘0’, so the

陷阱 3:电子表格中未补齐的日期。 有人手动编辑了我们的导出文件,其中一个单元格写着 2014-8-2。一个单元格,两个失败。Python 3.11 的 date.fromisoformat——自 3.11 起更友好,但对此仍然严格——拒绝了它: ValueError: Invalid isoformat string: '2014-8-2' 字符串比较也没有捕捉到它,因为 ‘2014-8-2’ < ‘2014-08-01’ 的计算结果为 False——‘8’ 在 ‘0’ 之后排序,所以……