πŸ“ŠTime Duration Calculator

Calculate exact time duration between two dates and times. Perfect for work hours, project tracking, event planning, and time management. Supports AM/PM, 24-hour format, and multiple time zones.

πŸ€” What Is a Time Duration Calculator?

Think of a stopwatch that measures any period in history - that's a time duration calculator! It precisely calculates the exact time between any two dates and times, perfect for tracking work hours, planning projects, counting down to events, or calculating your exact age.

:
:
⏰ Enter your start and end times above to calculate the duration

⚑ Quick Examples

πŸ“Š Standard Work Day
9:00 AM - 5:30 PM (8.5 hours)
πŸ’Ό Meeting Duration
2:15 PM - 3:45 PM (1.5 hours)
✈️ Flight Time
11:30 PM - 7:45 AM (+1 day)
πŸ“‹ Project Timeline
Jan 1 - Mar 15 (74 days)
πŸŒ™ Night Shift
10:00 PM - 6:00 AM (8 hours)
β˜• Break Time
12:00 PM - 1:00 PM (1 hour)
`; } else { const mainDisplay = formatDuration(result); container.innerHTML = `
${mainDisplay}
${formatDetailedDuration(result)}

Total Hours

${formatDecimal(result.totalHours)}
Decimal format

Total Minutes

${formatNumber(result.totalMinutes)}
In minutes

Total Seconds

${formatNumber(result.totalSeconds)}
In seconds
${result.days > 0 ? `

Calendar Days

${result.days}
Days included
` : ''}
`; } } // Format duration for main display function formatDuration(result) { if (result.days > 0) { return `${result.days}d ${result.hours}h ${result.minutes}m`; } else if (result.hours > 0) { return `${result.hours}h ${result.minutes}m`; } else { return `${result.minutes}m ${result.seconds}s`; } } // Format detailed duration description function formatDetailedDuration(result) { const parts = []; if (result.days > 0) parts.push(`${result.days} day${result.days !== 1 ? 's' : ''}`); if (result.hours > 0) parts.push(`${result.hours} hour${result.hours !== 1 ? 's' : ''}`); if (result.minutes > 0) parts.push(`${result.minutes} minute${result.minutes !== 1 ? 's' : ''}`); if (result.seconds > 0 && result.days === 0) parts.push(`${result.seconds} second${result.seconds !== 1 ? 's' : ''}`); return parts.join(', '); } // Set current time function setCurrentTime(type) { const now = new Date(); const hour12 = now.getHours() % 12 || 12; const minute = now.getMinutes(); const ampm = now.getHours() >= 12 ? 'PM' : 'AM'; if (type === 'start') { document.getElementById('startHour').value = hour12; document.getElementById('startMinute').value = minute.toString().padStart(2, '0'); document.getElementById('startAmPm').value = ampm; } else { document.getElementById('endHour').value = hour12; document.getElementById('endMinute').value = minute.toString().padStart(2, '0'); document.getElementById('endAmPm').value = ampm; } } // Sample usage function function useSample(sampleId) { const samples = { 'workday': () => { switchMode('time'); setSampleTime(9, 0, 'AM', 5, 30, 'PM'); }, 'meeting': () => { switchMode('time'); setSampleTime(2, 15, 'PM', 3, 45, 'PM'); }, 'flight': () => { switchMode('datetime'); const today = new Date(); const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1); document.getElementById('startDateTime').value = formatDateTimeLocal(today, 23, 30); document.getElementById('endDateTime').value = formatDateTimeLocal(tomorrow, 7, 45); }, 'project': () => { switchMode('business'); const start = new Date(2025, 0, 1); // Jan 1, 2025 const end = new Date(2025, 2, 15); // Mar 15, 2025 document.getElementById('startDate').value = formatDateOnly(start); document.getElementById('endDate').value = formatDateOnly(end); }, 'overtime': () => { switchMode('time'); setSampleTime(10, 0, 'PM', 6, 0, 'AM'); }, 'break': () => { switchMode('time'); setSampleTime(12, 0, 'PM', 1, 0, 'PM'); } }; if (samples[sampleId]) { samples[sampleId](); // Auto-calculate after setting values setTimeout(() => { calculateDuration(); }, 100); // Smooth scroll to results setTimeout(() => { document.getElementById('resultContainer').scrollIntoView({ behavior: 'smooth', block: 'center' }); }, 200); } } // Helper to set sample time function setSampleTime(startH, startM, startAP, endH, endM, endAP) { document.getElementById('startHour').value = startH; document.getElementById('startMinute').value = startM.toString().padStart(2, '0'); document.getElementById('startAmPm').value = startAP; document.getElementById('endHour').value = endH; document.getElementById('endMinute').value = endM.toString().padStart(2, '0'); document.getElementById('endAmPm').value = endAP; } // Format date for datetime-local input function formatDateTimeLocal(date, hour, minute) { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const h = hour.toString().padStart(2, '0'); const m = minute.toString().padStart(2, '0'); return `${year}-${month}-${day}T${h}:${m}`; } // Format date for date input function formatDateOnly(date) { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); return `${year}-${month}-${day}`; } // Copy results to clipboard function copyResults() { const resultMain = document.querySelector('.result-main').textContent; const resultInfo = document.querySelector('.result-info').textContent; const text = `Time Duration Calculation: Duration: ${resultMain} Details: ${resultInfo} Calculated using WIA Pin Code Time Duration Calculator: https://wiapincode.com/family/time-duration-calculator/`; copyToClipboard(text); } // Clear results function clearResults() { const container = document.getElementById('resultContainer'); container.innerHTML = `
⏰ Enter your start and end times above to calculate the duration
`; } // ========== UTILITY FUNCTIONS ========== // Format numbers with commas function formatNumber(num) { return new Intl.NumberFormat('en-US').format(Math.round(num)); } // Format decimal numbers function formatDecimal(num) { return new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 }).format(num); } // Copy to clipboard function copyToClipboard(text) { navigator.clipboard.writeText(text).then(() => { showNotification('Results copied to clipboard!', 'success'); }).catch(() => { // Fallback for older browsers const textArea = document.createElement('textarea'); textArea.value = text; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); showNotification('Results copied to clipboard!', 'success'); }); } // Show error function showError(elementId, message) { const errorElement = document.getElementById(elementId); if (errorElement) { errorElement.textContent = message; } } // Clear errors function clearErrors() { document.querySelectorAll('.error').forEach(el => el.textContent = ''); } // Show notification toast function showNotification(message, type = 'success') { const toast = document.createElement('div'); toast.className = `toast ${type}`; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.remove(); }, 3000); } // Show OTA section function showOTA() { const otaContainer = document.getElementById('otaContainer'); if (otaContainer && (otaContainer.style.display === 'none' || !otaContainer.style.display)) { otaContainer.style.display = 'block'; // Attention-grabbing pulse effect setTimeout(() => { const otaHeader = document.querySelector('.ota-header h3'); if (otaHeader) { otaHeader.style.animation = 'pulse 1s ease-in-out'; } }, 100); } } // Analytics tracking function trackEvent(eventName, data = {}) { if (typeof gtag !== 'undefined') { gtag('event', eventName, { 'event_category': TOOL_CONFIG.category, 'event_label': TOOL_CONFIG.name, ...data }); } } // ========== AI ASSISTANT FUNCTIONS ========== // AI λͺ¨λ‹¬ μ—΄κΈ° function openAIModal() { const modal = document.getElementById('aiModal'); if(modal) modal.classList.add('show'); if (aiModalState.apiKey && aiModalState.currentView === 'gemini') { showGeminiChat(); } else { showAISelector(); } updateAPIKeyStatus(); } // AI λͺ¨λ‹¬ λ‹«κΈ° function closeAIModal() { const modal = document.getElementById('aiModal'); if(modal) modal.classList.remove('show'); setTimeout(() => { aiModalState.currentView = 'selector'; showAISelector(); }, 300); } // AI 선택 ν™”λ©΄ ν‘œμ‹œ function showAISelector() { document.getElementById('aiModalTitle').textContent = 'Choose Your AI Assistant'; document.getElementById('aiSelector').style.display = 'flex'; document.getElementById('geminiChat').style.display = 'none'; document.getElementById('apiKeySetup').style.display = 'none'; aiModalState.currentView = 'selector'; } // Gemini μ±„νŒ… ν™”λ©΄ ν‘œμ‹œ function showGeminiChat() { document.getElementById('aiModalTitle').innerHTML = '✨ Gemini AI Assistant'; document.getElementById('aiSelector').style.display = 'none'; document.getElementById('geminiChat').style.display = 'flex'; document.getElementById('apiKeySetup').style.display = 'none'; aiModalState.currentView = 'gemini'; const chatMessages = document.getElementById('chatMessages'); if (!chatMessages.innerHTML.trim()) { addMessage('assistant', `Hello! I can help you with: β€’ Time calculations and conversions β€’ Work hour tracking and payroll β€’ Project timeline planning β€’ Time zone conversions β€’ Business day calculations β€’ Time management tips What would you like to know about time calculations?`); } } // API ν‚€ μ„€μ • ν™”λ©΄ ν‘œμ‹œ function showAPIKeySetup() { document.getElementById('aiModalTitle').textContent = 'Setup Gemini API'; document.getElementById('aiSelector').style.display = 'none'; document.getElementById('geminiChat').style.display = 'none'; document.getElementById('apiKeySetup').style.display = 'block'; aiModalState.currentView = 'setup'; } // AI 선택 처리 function selectAI(aiType) { switch(aiType) { case 'chatgpt': const toolContext = `I need help with time duration calculations using the Time Duration Calculator on WIA Pin Code platform. Current mode: ${currentMode}.`; const chatUrl = `https://chat.openai.com/?q=${encodeURIComponent(toolContext)}`; window.open(chatUrl, '_blank'); closeAIModal(); trackEvent('ai_selection', { ai_type: 'chatgpt' }); break; case 'claude': const claudeContext = `I need help with time duration calculations using the Time Duration Calculator on WIA Pin Code platform. Current mode: ${currentMode}.`; const claudeUrl = `https://claude.ai/chat?q=${encodeURIComponent(claudeContext)}`; window.open(claudeUrl, '_blank'); closeAIModal(); trackEvent('ai_selection', { ai_type: 'claude' }); break; case 'gemini': if (!aiModalState.apiKey) { showAPIKeySetup(); } else { showGeminiChat(); } trackEvent('ai_selection', { ai_type: 'gemini' }); break; } } // API ν‚€ μ €μž₯ function saveGeminiApiKey() { const apiKey = document.getElementById('geminiApiKeyInput').value.trim(); if (apiKey) { localStorage.setItem('geminiApiKey', apiKey); aiModalState.apiKey = apiKey; showGeminiChat(); updateAPIKeyStatus(); } else { alert('Please enter a valid API key'); } } // API ν‚€ μƒνƒœ μ—…λ°μ΄νŠΈ function updateAPIKeyStatus() { const statusEl = document.getElementById('apiKeyStatus'); if (aiModalState.apiKey) { statusEl.innerHTML = 'Change API Key'; } else { statusEl.textContent = 'No API key set'; } } // μ±„νŒ… λ©”μ‹œμ§€ μΆ”κ°€ function addMessage(type, content) { const chatMessages = document.getElementById('chatMessages'); const messageDiv = document.createElement('div'); messageDiv.className = `message ${type}`; if (type === 'user') { messageDiv.innerHTML = `You: ${content}`; } else { messageDiv.innerHTML = `✨ Gemini:
${content.replace(/\n/g, '
')}`; } chatMessages.appendChild(messageDiv); chatMessages.scrollTop = chatMessages.scrollHeight; } // Gemini에 λ©”μ‹œμ§€ 전솑 async function sendToGemini() { const input = document.getElementById('geminiInput'); const message = input.value.trim(); if (!message) return; addMessage('user', message); input.value = ''; const loadingMsg = document.createElement('div'); loadingMsg.className = 'message assistant'; loadingMsg.innerHTML = '✨ Gemini:
Thinking...'; loadingMsg.id = 'loading-message'; document.getElementById('chatMessages').appendChild(loadingMsg); try { const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${aiModalState.apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: `Context: User is using the Time Duration Calculator on WIA Pin Code platform. Current calculation mode: ${currentMode} This tool calculates time durations between dates/times, work hours, and business days. User question: ${message}` }] }], generationConfig: { temperature: 0.7, maxOutputTokens: 1000 } }) }); const data = await response.json(); document.getElementById('loading-message').remove(); if (data.candidates && data.candidates[0] && data.candidates[0].content) { const reply = data.candidates[0].content.parts[0].text; addMessage('assistant', reply); } else { addMessage('assistant', 'Sorry, I could not generate a response. Please try again.'); } } catch (error) { document.getElementById('loading-message')?.remove(); if (error.message.includes('API key')) { addMessage('error', 'Invalid API key. Please check your API key and try again.'); showAPIKeySetup(); } else { addMessage('error', 'Failed to connect to Gemini. Please check your internet connection and try again.'); } } } // ========== EVENT LISTENERS ========== document.addEventListener('DOMContentLoaded', function() { // Initialize default date/time values const now = new Date(); const hour = now.getHours(); const minute = now.getMinutes(); // Set default datetime values document.getElementById('startDateTime').value = formatDateTimeLocal(now, 9, 0); const defaultEnd = new Date(now); defaultEnd.setHours(17, 30); document.getElementById('endDateTime').value = formatDateTimeLocal(defaultEnd, 17, 30); // Set default date values document.getElementById('startDate').value = formatDateOnly(now); const defaultEndDate = new Date(now); defaultEndDate.setDate(defaultEndDate.getDate() + 30); document.getElementById('endDate').value = formatDateOnly(defaultEndDate); // Enter key support for all inputs document.querySelectorAll('.time-input, .input-field').forEach(input => { input.addEventListener('keypress', function(e) { if (e.key === 'Enter') { calculateDuration(); } }); }); // Clear errors on input document.querySelectorAll('.time-input, .input-field').forEach(input => { input.addEventListener('input', clearErrors); }); // AI λ²„νŠΌ 이벀트 document.getElementById('aiBtn').addEventListener('click', openAIModal); // λͺ¨λ‹¬ μ™ΈλΆ€ ν΄λ¦­μ‹œ λ‹«κΈ° document.getElementById('aiModal').addEventListener('click', function(e) { if (e.target === this) { closeAIModal(); } }); // μ—”ν„° ν‚€ 지원 및 ESC ν‚€λ‘œ λͺ¨λ‹¬ λ‹«κΈ° document.addEventListener('keydown', function(e) { if (e.key === 'Enter') { const geminiInput = document.getElementById('geminiInput'); if (document.activeElement === geminiInput) { sendToGemini(); } } if (e.key === 'Escape') { closeAIModal(); } }); // 초기 API ν‚€ μƒνƒœ μ—…λ°μ΄νŠΈ updateAPIKeyStatus(); updateCurrentYear(); updateToolCount(); }); // ========== DYNAMIC TOOL COUNT ========== async function updateToolCount() { try { const response = await fetch('/api/tool-count.php'); const data = await response.json(); document.querySelectorAll('.dynamic-tools-count').forEach(el => { el.textContent = `${data.count}+ free productivity tools in 211 languages. No signup, no fees, just tools that work.`; }); document.querySelectorAll('.dynamic-count').forEach(el => { const prefix = el.getAttribute('data-text') || ''; const suffix = el.getAttribute('data-suffix') || ''; const icon = el.textContent.split(' ')[0] || ''; el.textContent = `${icon} ${prefix} ${data.count}+ ${suffix}`; }); } catch (error) { const fallbackCount = 333; document.querySelectorAll('.dynamic-tools-count').forEach(el => { el.textContent = `${fallbackCount}+ free productivity tools in 211 languages. No signup, no fees, just tools that work.`; }); document.querySelectorAll('.dynamic-count').forEach(el => { const prefix = el.getAttribute('data-text') || ''; const suffix = el.getAttribute('data-suffix') || ''; const icon = el.textContent.split(' ')[0] || ''; el.textContent = `${icon} ${prefix} ${fallbackCount}+ ${suffix}`; }); } } function updateCurrentYear() { const currentYear = new Date().getFullYear(); document.querySelectorAll('.current-year').forEach(el => { el.textContent = currentYear; }); } // ========== ANALYTICS ========== window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX'); trackEvent('page_view', { tool: TOOL_CONFIG.name, category: TOOL_CONFIG.category });