4
2

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 5 years have passed since last update.

Moment.jsを使って年齢計算

Last updated at Posted at 2019-12-24

サンプル

sample.js
import moment from "moment";

function calcAge() {
  dateOfBirth = moment(new Date("1994-01-01")); // 生年月日
  today = moment(new Date("2019-12-24")); // 今日の日付

  // 西暦を比較して年齢を算出
  let baseAge = today.year() - dateOfBirth.year(); // >> 2019 - 1994 = 25(歳)

  // 誕生日を作成 >> 2019-01-01
  let birthday = moment(
    new Date(
      today.year() + "-" + (dateOfBirth.month() + 1) + "-" + dateOfBirth.date()
    )
  );
  console.log(birthday) // >> 2019-01-01

  // 今日が誕生日より前の日付である場合、算出した年齢から-1した値を返す
  if (today.isBefore(birthday)) {
    return baseAge - 1; // 24(歳)が返却される
  }

  // 今日が誕生日 または 誕生日を過ぎている場合は算出した年齢をそのまま返す
  return baseAge; // 25(歳)が返却される
}

 
他にも。

moment1.isAfter(moment2) // moment1がmoment2より未来の日付かどうか
moment1.isSame(moment2, "day")・・・moment1とmoment2が同じ日付かどうか
// "month"を指定した場合は、年月が同じかどうか
// "year"を指定した場合は、西暦が同じかどうか

 

正しい日付かどうか

sample.js
import moment from "moment";

/**
 * 年齢計算
 *
 * @param {Date} baseday
 * @param {Date} birthday
 */
function calcAge(baseday, birthday) {
  console.log(moment(baseday).isValid()); // 正しい日付ならtrue, 不正な日付はfalse
  console.log(moment(birthday).isValid());
}
4
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?