4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

データベースのDate型に日付のみを保存するときの年数には9999ではなく8888を使おう

Last updated at Posted at 2020-12-22

例えば、ユーザの誕生日をデータベースに追加するを想定します。

この場合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のように、閏年をマジックナンバーにしましょう、という話でした。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?