4
1

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.

JavaScriptでいま何歳?

Posted at

いま何歳?
年齢とか何周年?を計算するためのコードを書いたのでメモ。

Dateオブジェクトを使う

const now = new Date()
const thisYear = now.getFullYear()
const thisMonth = now.getMonth() + 1
const today = now.getDate()
const calcAge = birthday => {
  let target = thisYear * 10000 + thisMonth * 100 + today
  return Math.floor((target - birthday) / 10000)
}

console.log(`いま${calcAge(20001221)}歳です`)

参考:MDN: Date

Moment.jsを使う

moment()を呼び出すと、DateオブジェクトをラップするMomentオブジェクトを生成してくれる。

import moment from 'moment'

const now = moment()
const birthday = moment('2000-12-21')
const calcAge = now.diff(birthday, 'year')

console.log(`いま${calcAge}歳です`)

Dateオブジェクトを使うよりも、シンプルに日付関連を扱えそう。

参考:公式ドキュメント: Moment.js Documentation

4
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?