Hari 23: Date & Time di PHP
55 min
Last updated 09 Apr 2026
Fungsi Date & Time
// date() — format tanggal sekarang
echo date("Y-m-d"); // 2024-05-15
echo date("d/m/Y H:i:s"); // 15/05/2024 14:30:00
echo date("D, d M Y"); // Wed, 15 May 2024
// mktime() — timestamp dari komponen
$ts = mktime(0, 0, 0, 12, 25, 2024); // Natal 2024
echo date("d F Y", $ts); // 25 December 2024
// time() — timestamp sekarang
echo time(); // 1715775000 (unix timestamp)
Kelas DateTime
$tgl = new DateTime("2024-01-15");
$sekarang = new DateTime();
// Hitung selisih
$diff = $sekarang->diff($tgl);
echo $diff->days . " hari yang lalu\n";
// Manipulasi
$tgl->modify("+1 month");
$tgl->modify("-5 days");
echo $tgl->format("Y-m-d");
// DateTimeImmutable — tidak berubah
$dt = new DateTimeImmutable("2024-06-01");
$next = $dt->modify("+7 days"); // return baru, $dt tetap
echo $next->format("Y-m-d"); // 2024-06-08
💡
Notice: $date1->diff($date2) return DateInterval. Properti ->days berisi total hari, ->y tahun, ->m bulan.
Assignment
Hitung berapa hari dari 1 Januari 2024 sampai 17 Agustus 2024 (HUT RI ke-79). Tampilkan "Selisih: X hari".
Expected output:
Selisih: 229 hari
PHP
index.php
Solution
Output