import React, { useState, useEffect } from 'react'; // Main App component const App = () => { // State variables for input value, from unit, to unit, and converted result const [inputValue, setInputValue] = useState(''); const [fromUnit, setFromUnit] = useState('seconds'); const [toUnit, setToUnit] = useState('minutes'); const [convertedResult, setConvertedResult] = useState(''); // Define conversion rates to a base unit (seconds) // Using seconds as the base unit for all conversions const conversionRates = { seconds: 1, minutes: 60, // 1 minute = 60 seconds hours: 3600, // 1 hour = 60 minutes * 60 seconds/minute days: 86400, // 1 day = 24 hours * 3600 seconds/hour weeks: 604800, // 1 week = 7 days * 86400 seconds/day years: 31536000, // 1 year = 365 days * 86400 seconds/day (simplified) }; // Effect hook to perform conversion whenever relevant state changes useEffect(() => { convertTime(); }, [inputValue, fromUnit, toUnit]); // Dependencies for the effect const handleInputChange = (e) => { // Allow only numbers and a single decimal point const value = e.target.value; if (/^\d*\.?\d*$/.test(value)) { setInputValue(value); } }; const convertTime = () => { const value = parseFloat(inputValue); // If the input value is not a valid number, clear the result if (isNaN(value)) { setConvertedResult(''); return; } // Convert the input value to seconds (base unit) const valueInSeconds = value * conversionRates[fromUnit]; // Convert the value from seconds to the target unit const result = valueInSeconds / conversionRates[toUnit]; // Set the converted result, formatted to 6 decimal places setConvertedResult(result.toFixed(6)); }; return ( ); }; export default App;
🕒 Time Converter
{} {} {} {}
{convertedResult || '0.00'}