getSeconds()
ES1+Returns the seconds (0-59) in the specified date according to local time.
Syntax
date.getSeconds()Return Value
number
A number (0-59) representing the seconds
Examples
JavaScript
const date = new Date('2024-01-15T14:30:45');
console.log(date.getSeconds()); Output:
// 45
📌 When to Use
Use getSeconds() for countdown timers, stopwatch applications, or displaying full time with seconds precision.
⚠️ Common Mistakes
Using getSeconds() for elapsed time measurement instead of getTime() difference.
✅ Best Practices
For timers, calculate elapsed seconds from timestamps: Math.floor((Date.now() - startTime) / 1000).
⚡ Performance Notes
getSeconds() is O(1). For animation frame timing, use requestAnimationFrame with timestamp parameter instead.
🌍 Real World Example
Countdown Timer
Display a countdown timer showing hours, minutes, and seconds remaining.
function getCountdown(targetDate) {
const now = Date.now();
const target = new Date(targetDate).getTime();
const diff = target - now;
if (diff <= 0) return { expired: true };
const hours = Math.floor(diff / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
return {
expired: false,
hours: String(hours).padStart(2, '0'),
minutes: String(minutes).padStart(2, '0'),
seconds: String(seconds).padStart(2, '0'),
display: `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
};
}
console.log(getCountdown('2024-12-31T23:59:59'));