Menu

Creating the Calculator App

Creating the Calculator App

This file contains the complete logic and UI of the Age Calculator. It manages the state (dob), handles the DatePicker, calculates age with the calculateAge function, and displays the final result via conditional rendering.

File Path: Age_Calculator\src\components\AgeCalculator.jsx

import React, { useState } from "react";
import dayjs from "dayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

function AgeCalculator() {
  const currentDate = dayjs();
  const [dob, setDob] = useState(null);

  const calculateAge = (birthDate) => {
    if (!birthDate) return { years: 0, months: 0 };

    let years = currentDate.year() - birthDate.year();
    let months = currentDate.month() - birthDate.month();

    if (months < 0) {
      years--;
      months += 12;
    }

    if (currentDate.date() < birthDate.date()) {
      months--;
      if (months < 0) {
        years--;
        months += 12;
      }
    }

    return { years, months };
  };

  return (
    <>
      {" "}
      <div className="main-wrapper flex flex-col items-center w-full min-h-screen pt-8">
        <h1 className="mb-6 text-2xl md:text-3xl text-red-500">
          Age Calculator
        </h1>
        <div className="age-calculator-component w-[90%] md:w-[70%] lg:w-[50%] xl:w-[40%] py-5 px-2">
          <p className="text-head text-base md:text-xl text-center">
            Please enter your date of birth in MM/DD/YYYY format
          </p>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <DatePicker
              value={dob}
              maxDate={currentDate}
              onChange={(newValue) => setDob(newValue)}
              slotProps={{
                textField: { sx: { bgcolor: "#fff" } },
              }}
            />
          </LocalizationProvider>
          <div className="age-text">
            <p className="text-base md:text-xl p-2 lg:p-3">
              Your age is:{" "}
              {dob
                ? (() => {
                    const { years, months } = calculateAge(dob);
                    if (years === 0) return `${months} months`;
                    if (months === 0) return `${years} years`;
                    return `${years} years ${months} months`;
                  })()
                : ""}
            </p>
          </div>
        </div>
      </div>
    </>
  );
}

export default AgeCalculator;