PHP Date and Time

PHP provides robust support for working with dates and times through built-in functions and the DateTime class. Here's a quick overview with examples:


1. Getting Current Date and Time

echo date("Y-m-d H:i:s"); // Output: 2025-05-03 14:30:00
  • Y = 4-digit year

  • m = 2-digit month

  • d = 2-digit day

  • H:i:s = Hour, minutes, seconds (24-hour format)


2. Changing the Timezone

date_default_timezone_set("America/New_York"); echo date("Y-m-d H:i:s"); // Time in New York

3. Formatting Dates

echo date("l, F j, Y"); // Output: Saturday, May 3, 2025

4. Creating a DateTime Object

$dt = new DateTime("2025-05-03 14:00:00"); echo $dt->format("Y-m-d H:i:s");

5. Modifying Dates

$dt->modify("+1 day"); echo $dt->format("Y-m-d"); // Output: 2025-05-04

6. Date Difference

$start = new DateTime("2025-05-01"); $end = new DateTime("2025-05-03"); $diff = $start->diff($end); echo $diff->days; // Output: 2

7. Timestamps

echo time(); // Unix timestamp echo date("Y-m-d H:i:s", 1720000000); // Convert timestamp to date