1. //根据日期算年龄
    2. function mymethod(birthday){
    3. if(birthday){
    4. birthday=birthday.split('-');
    5. // 新建日期对象
    6. let date = new Date();
    7. // 今天日期,数组,同 birthday
    8. let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
    9. // 分别计算年月日差值
    10. let age = today.map((val, index) => {
    11. return val - birthday[index]
    12. })
    13. // 当天数为负数时,月减 1,天数加上月总天数
    14. if (age[2] < 0) {
    15. // 简单获取上个月总天数的方法,不会错
    16. let lastMonth = new Date(today[0], today[1], 0)
    17. age[1]--
    18. age[2] += lastMonth.getDate()
    19. }
    20. // 当月数为负数时,年减 1,月数加上 12
    21. if (age[1] < 0) {
    22. age[0]--
    23. age[1] += 12
    24. }
    25. return(age[0]+'岁'+age[1]+'月'+age[2]+'天');
    26. }
    27. }
    28. console.log(mymethod('1997-7-15'), 'nnnnnnnnnn')
    29. 版权声明:本文为CSDN博主「冉、」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    30. 原文链接:https://blog.csdn.net/weixin_51697449/article/details/120488495