Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【js计算年龄】 #71

Open
kind-hearted opened this issue Jan 14, 2019 · 0 comments
Open

【js计算年龄】 #71

kind-hearted opened this issue Jan 14, 2019 · 0 comments

Comments

@kind-hearted
Copy link
Owner

function addDays(date, days) {
  var diff = days * 24 * 60 * 60 * 1000;

  return new Date(date.getTime() + diff);
}

function formatYMD(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;

  return year + '-' + month + '-' + day;
}

// console.log(formatYMD(new Date()) === '2019-01-14');
// console.log(formatYMD(new Date(2018, 0, 9)) === '2018-01-09');
// console.log(formatYMD(addDays(new Date(), 2)) === '2019-01-16');
// console.log(formatYMD(addDays(new Date(), 30)) === '2019-02-13');

function getAgeByYMD(birthday, end) {
	birthday = birthday.split('-');
  end = end.split('-');

  var years = end[0] - birthday[0];
  var diffMonth = end[1] - birthday[1];

  if (diffMonth < 0 || (diffMonth === 0 && (end[2] - birthday[2]) < 0)) {
    years = years - 1;
  }

  return years;
}
console.log(getAgeByYMD('1990-01-01', formatYMD(new Date())) === 29);
console.log(getAgeByYMD('1990-01-14', formatYMD(new Date())) === 29);
console.log(getAgeByYMD('1990-01-15', formatYMD(new Date())) === 28);
console.log(getAgeByYMD('1990-02-15', formatYMD(new Date())) === 28);
console.log(getAgeByYMD('1959-01-14', formatYMD(new Date())) === 60);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant