gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
write a javascript function to calculate the duration between two dates that takes an…
- User
write a javascript function to calculate the duration between two dates that takes an optional paramter to determine whether the outupt should be in seconds, minutes, days, months, or years
- Assistant
Here's a JavaScript function that calculates the duration between two dates and allows you to specify the desired output format:
function calculateDuration(startDate, endDate, outputFormat = 'seconds') { const diffInMilliseconds = Math.abs(endDate - startDate); switch (outputFormat.toLowerCase()) { case 'seconds': return diffInMilliseconds / 1000; case 'minutes': return diffInMilliseconds / (1000 * 60); case 'hours': return diffInMilliseconds / (1000 * 60 * 60); case 'days': return diffInMilliseconds / (1000 * 60 * 60 * 24); case 'months': const diffInMonths = (endDate.getFullYear() - startDate.getFullYear()) * 12 + (endDate.getMonth() - startDate.getMonth()); return diffInMonths; case 'years': return endDate.getFullYear() - startDate.getFullYear(); default: throw new Error('Invalid output format.'); } }