Metode Tanggal Tetapkan JavaScript
Metode Atur Tanggal memungkinkan Anda mengatur nilai tanggal (tahun, bulan, hari, jam, menit, detik, milidetik) untuk Objek Tanggal.
Tetapkan Metode Tanggal
Metode Set Date digunakan untuk mengatur bagian dari tanggal:
Method | Description |
---|---|
setDate() | Set the day as a number (1-31) |
setFullYear() | Set the year (optionally month and day) |
setHours() | Set the hour (0-23) |
setMilliseconds() | Set the milliseconds (0-999) |
setMinutes() | Set the minutes (0-59) |
setMonth() | Set the month (0-11) |
setSeconds() | Set the seconds (0-59) |
setTime() | Set the time (milliseconds since January 1, 1970) |
Metode setFullYear()
Metode setFullYear()
ini menetapkan tahun dari objek tanggal. Dalam contoh ini hingga 2020:
Contoh
const d = new Date();
d.setFullYear(2020);
Metode ini secara opsionalsetFullYear()
dapat mengatur bulan dan hari:
Contoh
const d = new Date();
d.setFullYear(2020, 11, 3);
Metode setMonth()
Metode setMonth()
ini menetapkan bulan dari objek tanggal (0-11):
Contoh
const d = new Date();
d.setMonth(11);
Metode setDate()
Metode setDate()
ini menetapkan hari objek tanggal (1-31):
Contoh
const d = new Date();
d.setDate(15);
Metode setDate()
ini juga dapat digunakan untuk menambahkan hari ke tanggal:
Contoh
const d = new Date();
d.setDate(d.getDate() + 50);
Jika penambahan hari menggeser bulan atau tahun, perubahan akan ditangani secara otomatis oleh objek Date.
Metode setHours()
Metode setHours()
ini menetapkan jam objek tanggal (0-23):
Contoh
const d = new Date();
d.setHours(22);
Metode setMinutes()
Metode setMinutes()
ini menetapkan menit dari objek tanggal (0-59):
Contoh
const d = new Date();
d.setMinutes(30);
Metode setSeconds()
Metode setSeconds()
ini menetapkan detik dari objek tanggal (0-59):
Contoh
const d = new Date();
d.setSeconds(30);
Bandingkan Tanggal
Tanggal dapat dengan mudah dibandingkan.
Contoh berikut membandingkan tanggal hari ini dengan 14 Januari 2100:
Contoh
let text = "";
const today = new Date();
const someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
JavaScript menghitung bulan dari 0 hingga 11. Januari adalah 0. Desember adalah 11.
Referensi Tanggal JavaScript Lengkap
Untuk referensi Tanggal lengkap, kunjungi:
Referensi Tanggal JavaScript Lengkap .
Referensi berisi deskripsi dan contoh semua properti dan metode Tanggal.