Sobes.tech
Junior

What does the DateTime class implement in PHP?

sobes.tech AI

Answer from AI

The DateTime class provides extensive capabilities for working with dates and times:

  • Creating and representing moments in time with timezone awareness.
  • Performing arithmetic operations (adding/subtracting intervals, comparing dates).
  • Formatting dates and times into various strings.
  • Parsing strings into DateTime objects.
<?php
// Creating a DateTime object for the current moment
$now = new DateTime();
echo $now->format('Y-m-d H:i:s'); // Formatting output

echo "\n";

// Creating a DateTime object from a string
$date_string = '2023-10-27 10:30:00';
$specific_date = new DateTime($date_string);
echo $specific_date->format('l, F jS, Y'); // Different format

echo "\n";

// Adding an interval
$interval = new \DateInterval('P1D'); // Interval of one day
$tomorrow = $specific_date->add($interval);
echo $tomorrow->format('Y-m-d');

echo "\n";

// Difference between dates
$diff = $now->diff($specific_date);
echo $diff->format('%R%a days'); // Displaying difference in days
?>