【问题标题】:How to Calculate next birthday using react js?如何使用 react js 计算下一个生日?
【发布时间】:2022-06-16 17:58:42
【问题描述】:

当前出生日期详细信息如下: Date: "1998-06-16T21:50:20.750Z", Age: 24

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    让我们假设您的日期对象是一个字符串。那么,下面的方法应该会有所帮助。唯一的问题是它没有考虑到 2 月 29 日的生日。必须根据要求进行处理

    function nextBirthday(birthDate){
        const birthDateObj = new Date(birthDate);
        const today =  new Date();
        let nextBirthday = new Date(today.getFullYear(),birthDateObj.getMonth(),birthDateObj.getDate());
    
        if(nextBirthday<today){
            nextBirthday.setFullYear(today.getFullYear()+1)
        }
    
        console.log(nextBirthday.toString())
        return nextBirthday
    }
    
    nextBirthday("1998-05-16T00:00:00.000Z");
    

    P.S - 您可以直接单独使用 Javascript 来完成此操作(在 React 中也是如此)

    评论答案:

    function nextBirthday(birthDate){
        const birthDateObj = new Date(birthDate);
        const today =  new Date();
        let nextBirthday = new Date(today.getFullYear(),birthDateObj.getMonth(),birthDateObj.getDate());
    
        if(nextBirthday<today){
            nextBirthday.setFullYear(today.getFullYear()+1)
        }
    
        return nextBirthday
    }
    
    function daysBetweenDates(laterDate, earlierDate) {
    const timeDifference = laterDate.getTime()-earlierDate.getTime(); //gets time difference between 2 dates in milliseconds 
    const daysDifference = Math.ceil( timeDifference/(1000*60*60*24));
    return daysDifference
    }
    
    
    console.log(daysBetweenDates(nextBirthday("1998-05-16T00:00:00.000Z"),new Date()));

    【讨论】:

    • 如何计算下个生日还剩多少天?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    相关资源
    最近更新 更多