screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState, useEffect } = React; function TimeAgo({ timestamp }) { const [timeAgo, setTimeAgo] = useState(calculateTimeAgo(timestamp)); useEffect(() => { const interval = setInterval(() => { const timeAgoString = calculateTimeAgo(timestamp); setTimeAgo(timeAgoString); }, 1000); // Update every second return () => clearInterval(interval); }, [timestamp]); function calculateTimeAgo(timestamp) { const now = new Date(); const secondsElapsed = Math.floor((now - timestamp) / 1000); if (secondsElapsed < 60) { return `${secondsElapsed} seconds ago`; } else if (secondsElapsed < 3600) { const minutes = Math.floor(secondsElapsed / 60); return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`; } else if (secondsElapsed < 86400) { const hours = Math.floor(secondsElapsed / 3600); return `${hours} hour${hours !== 1 ? 's' : ''} ago`; } else { const days = Math.floor(secondsElapsed / 86400); return `${days} day${days !== 1 ? 's' : ''} ago`; } } return <span>{timeAgo}</span>; } function App() { const timestamp = new Date('2023-08-22 13:00:00'); // Replace with your timestamp return ( <div className="container"> <h3>React Js Convert Timestamp to time age Example</h3> <p>Posted <TimeAgo timestamp={timestamp} /></p> </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> /* Container */ .container { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); text-align: center; } </style> </body> </html>