Share feedback, ideas and get community help

F
Freyze
Offline, last seen 3 months ago
Joined September 13, 2024
Hello, I would like to make a script that calculates the age of a person from his date of birth, using the "Date" module, I’m not an expert in JavaScript code but I had help from Microsoft’s Copilot.
Unfortunately it doesn’t really work

here’s my code:
Plain Text
const birthDateString = "{{DateDeNaissance}}"; // Utilisez la variable définie dans Typebot
setVariable('Log1', `Date de naissance : ${birthDateString}`);

if (birthDateString && birthDateString.includes('/')) {
    const [year, month, day] = birthDateString.split('/');
    setVariable('Log2', `Jour : ${day}, Mois : ${month}, Année : ${year}`);

    if (day && month && year) {
        const birthDate = new Date(`${year}/${month}/${day}`);
        setVariable('Log3', `Date de naissance formatée : ${birthDate}`);

        if (!isNaN(birthDate)) {
            const today = new Date();
            let age = today.getFullYear() - birthDate.getFullYear();
            const monthDifference = today.getMonth() - birthDate.getMonth();

            if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }

            setVariable('Log4', `Âge calculé : ${age}`);
            setVariable('Age', age);
            return { Age: age };
        } else {
            setVariable('Log5', "Date de naissance invalide");
            return { Age: "Date de naissance invalide" };
        }
    } else {
        setVariable('Log6', "Format de date incorrect");
        return { Age: "Format de date incorrect" };
    }
} else {
    setVariable('Log7', "Date de naissance non définie ou format incorrect");
    return { Age: "Date de naissance non définie ou format incorrect" };
}


And the return of my results:
Plain Text
14/05/2002

Log 1 : Date de naissance : vhi3uwujq9ghn6ttu0czkh2ef
Log 2 : 
Log 3 : 
Log 4 : 
Log 5 : 
Log 6 : 
Log 7 : Date de naissance non définie ou format incorrect
2 comments
B