Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức Date.getUTCMonth() trong JavaScript

Phương thức getUTCMonth() trả về tháng (0-11) của đối tượng Date theo thời gian UTC. Tương tự getMonth(), tháng là 0-based (0 = Tháng 1).

Cú pháp

dateObj.getUTCMonth()
  • Trả về: Số nguyên 0-11
  • Không nhận tham số

Ví dụ cơ bản

const date = new Date('1989-09-26T12:04:25.096Z');
console.log(date.getUTCMonth()); // 8 (Tháng 9)

Thiếu tháng

const date = new Date('1989T12:04:25.096Z'); // Chỉ có năm
console.log(date.getUTCMonth()); // 0 (Tháng 1 - mặc định)

Ngày hiện tại UTC

const now = new Date();
console.log(now.getUTCMonth()); // Tháng UTC hiện tại

So sánh Local vs UTC Month

// Giả sử UTC+7, ngày 26/9 23:00 local = 27/9 16:00 UTC
const date = new Date('1989-09-26T23:00:00'); // Local

console.log("Local month:", date.getMonth());    // 8 (Tháng 9)
console.log("UTC month:",   date.getUTCMonth()); // 8 (Vẫn tháng 9 vì chưa qua nửa đêm UTC)

// Ngày 26/9 23:30 local = 27/9 16:30 UTC
const date2 = new Date('1989-09-26T23:30:00');
console.log("Local:", date2.getMonth());    // 8
console.log("UTC:",   date2.getUTCMonth()); // 8

// Ngày 26/9 18:00 local = 27/9 11:00 UTC (qua nửa đêm UTC)
const date3 = new Date('1989-09-26T18:00:00'); // UTC+7 -> 11:00 UTC same day
// Cần ví dụ qua ngày UTC:
const date4 = new Date('1989-09-26T20:00:00'); // 13:00 UTC same day
// Thực sự qua ngày UTC khi local time >= 17:00 (UTC+7)
const date5 = new Date('1989-09-26T17:00:00'); // 10:00 UTC same day
// Ví dụ rõ ràng hơn:
const date6 = new Date(Date.UTC(1989, 8, 26, 23, 0, 0)); // 26/9 23:00 UTC
console.log("UTC month:", date6.getUTCMonth()); // 8
const date7 = new Date(Date.UTC(1989, 8, 26, 23, 0, 0) + 2*3600*1000); // 27/9 01:00 UTC
console.log("UTC month:", date7.getUTCMonth()); // 8 (vẫn tháng 9)
const date8 = new Date(Date.UTC(1989, 8, 30, 23, 0, 0)); // 30/9 23:00 UTC
const date9 = new Date(date8.getTime() + 2*3600*1000); // 1/10 01:00 UTC
console.log("UTC month:", date9.getUTCMonth()); // 9 (Tháng 10)

Ứng dụng

  • Hệ thống quốc tế: lưu UTC, hiển thị local
  • Báo cáo theo tháng UTC (consistent across timezones)
  • Cron job chạy theo UTC

Lưu ý

  • Tháng 0-based (0-11)
  • Khác với getMonth() (local)
  • Trả về NaN nếu Date invalid
  • Cặp đôi với setUTCMonth()