例えば、ユーザの誕生日をデータベースに追加するを想定します。
この場合MySQL等ではDate型を使用すると思いますが、誕生日を設定していないユーザの誕生日は、9999-07-07
のように保存することになるでしょう。
すると、JavaScriptではnew Date()
したときに、null
の場合と区別がつけられます。
const dateFormatter = (string) => {
const date = new Date(string)
// 引数がnullの場合
if (date.getFullYear() === 1970) {
return null
} else if (date.getFullYear() === 9999) {
return format(date, 'M月 d日')
} else {
return `${format(date, 'y年 M月 d日')}(${differenceInYears(new Date(), date)}歳)`
}
}
dateFormatter('9999-7-7')
// 7月 7日
dateFormatter('2020-7-7')
// 2019年 7月 7日 (1歳)
しかし、このシステムでは、しばらくした後にエラーが発生します。
ユーザの誕生日が2月29日だったときです。
MySQLでは、9999-2-29
という存在しない日付をDate型に挿入できません。
なので、8888-2-29
のように、閏年をマジックナンバーにしましょう、という話でした。