Age calculator
rce https://esm.sh/react@18.2.0 */
import React, { useState } from "https://esm.sh/react@18.2.0";
import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
type CalculationMode = 'years' | 'months' | 'days';
function AgeCalculator() {
const [birthDate, setBirthDate] = useState('');
const [calculationMode, setCalculationMode] = useState('years');
const [age, setAge] = useState<{years: number, months: number, days: number} | null>(null);
const calculateAge = () => {
const today = new Date();
const birth = new Date(birthDate);
if (isNaN(birth.getTime())) {
alert('Please enter a valid date');
return;
}
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
let days = today.getDate() - birth.getDate();
// Adjust calculations if current month/day is before birth month/day
if (months < 0 || (months === 0 && days < 0)) {
years--;
months += 12;
}
if (days < 0) {
const lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
days += lastMonth.getDate();
months--;
}
setAge({ years, months, days });
};
const formatResult = () => {
if (!age) return null;
switch (calculationMode) {
case 'years':
return `🎂 ${age.years} years old`;
case 'months':
const totalMonths = age.years * 12 + age.months;
return `🕰️ ${totalMonths} months old`;
case 'days':
const totalDays =
age.years * 365 +
age.months * 30 +
age.days;
return `📅 ${totalDays} days old`;
}
};
return (
);
}
if (typeof document !== "undefined") { client(); }
export default async function server(request: Request) {
return new Response(`
Age Calculator
`, {
headers: { "content-type": "text/html" }
});
}
)}
);
}
function client() {
createRoot(document.getElementById("root")).render(
Comments
Post a Comment