Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน Date.getSeconds() ใน JavaScript

Date.getSeconds() คืออะไร

เมธอด Date.prototype.getSeconds() คืนค่า วินาที (seconds) ของ Date object ตาม เวลาท้องถิ่น (local time) ค่าที่ได้อยู่ในช่วง 0-59

ไวยากรณ์ (Syntax)

dateObj.getSeconds()

คืนค่า: จำนวนเต็ม 0-59 แทนวินาที

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1: การใช้งานพื้นฐาน

const date = new Date('1989-09-26T12:04:25.096');
console.log(date.getSeconds()); // 25

ตัวอย่างที่ 2: ไม่ได้ระบุวินาที

const date = new Date('1989-09-26T12:04'); // ไม่มีวินาที
console.log(date.getSeconds()); // 0 (default)

ตัวอย่างที่ 3: เวลาปัจจุบัน

const now = new Date();
console.log(`วินาทีปัจจุบัน: ${now.getSeconds()}`);
// ผลลัพธ์เปลี่ยนไปทุกวินาที

ตัวอย่างที่ 4: ค่าที่ล้น (Overflow Handling)

// วินาที 100 -> จะถูก normalize
const date = new Date('1989-09-26T04:50:100');
console.log(date.getSeconds()); // 40 (100 - 60 = 40, นาทีเพิ่ม 1)
// หมายเหตุ: ตัวอย่างเดิมแสดง 0 ซึ่งอาจเป็นพฤติกรรมเก่าหรือ bug
// มาตรฐานปัจจุบัน: จะ normalize อัตโนมัติ

UTC Version: getUTCSeconds()

const date = new Date('1989-09-26T12:04:25.096Z');

console.log('Local seconds:', date.getSeconds());     // ขึ้นกับ timezone
console.log('UTC seconds:', date.getUTCSeconds());    // 25 เสมอ

กรณีการใช้งานทั่วไป

  • Clock display: แสดงนาฬิกา real-time
  • Countdown timers: คำนวณเวลาที่เหลือ
  • Time formatting: สร้างสตริงเวลา HH:MM:SS
  • Scheduling: ตรวจสอบว่าถึงวินาทีที่กำหนดหรือยัง
  • Animation timing: Frame-accurate timing

ตัวอย่าง: Digital Clock

function formatTime(date = new Date()) {
  const h = String(date.getHours()).padStart(2, '0');
  const m = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${h}:${m}:${s}`;
}

setInterval(() => {
  console.clear();
  console.log(formatTime());
}, 1000);

ข้อควรระวัง

  • คืนค่า local time - ใช้ getUTCSeconds() สำหรับ UTC
  • ค่าอยู่ในช่วง 0-59 เสมอ (normalize อัตโนมัติ)
  • Invalid Date -> คืนค่า NaN
  • ไม่รองรับ leap seconds (JavaScript ไม่มี leap second support)