import formatToDate from './formatToDate';

/**
 * 根据出生时间获取生日
 * @param {Date|number|string} time
 * @returns {number}
 *
 * // 执行时间：2021-11
 * getAgeByBirth(new Date());   // => 0
 * getAgeByBirth('2011-01-01'); // => 10
 * getAgeByBirth(820454400000); // => 25
 */
function getAgeByBirth(time) {
  var age = -1;
  var birthDate = formatToDate(time);
  if (!birthDate) return age;
  var nowDate = new Date();
  var nowMonth = nowDate.getMonth();
  var birthMonth = birthDate.getMonth();
  age = nowDate.getFullYear() - birthDate.getFullYear();

  if (nowMonth < birthMonth || nowMonth === birthMonth && nowDate.getDate() < birthDate.getDate()) {
    age--;
  }

  return age;
}

export default getAgeByBirth;
