How to create a DateTime object

Using the current date and time

$now = new DateTime();

$Now = 06/18/2025 03:06

Using a strtotime() format string

$expires = new DateTime('2018-03-15 13:30:00');
$tomorrow = new DateTime('+1 day');
$due_date = new DateTime('+3 weeks');
$appointment = new DateTime('next Friday +1 week 13:30');
echo("<p>Appoingtment: $appointment.</p>\n");

$1ppointment = 06/27/2025 01:06

How to use the methods of a DateTime object

How to copy a DateTime object

$invoice_date = new DateTime('2017-09-15 13:30:00');
echo("<p>\$invoice_date = " . $invoice_date->format('m/d/Y h:m') . "</p>\n");
$due_date = clone $invoice_date;
echo("<p>\$due_date = " . $due_date->format('m/d/Y h:m') . "</p>>\n");

$invoice_date = 09/15/2017 01:09

$due_date = 09/15/2017 01:09

How to set the time and date of a DateTime object

$due_date->setTime(22, 30, 0); // 10:30 pm
$due_date->setDate(2017, 9, 15); // 9/15/2017

How to modify a DateTime object

$due_date->modify('+3 weeks');
echo("<p>$due_date = " . $due_date->format('m/d/Y h:m') . "</p>\n");

$due_date = 10/06/2017 10:10

How to display a DateTime object

echo("<p>Payment Due: " . $due_date->format('M. j, Y \a\t g:i a') . "</p>\n");

Payment Due: Oct. 6, 2017 at 10:30 pm

How to convert a timestamp to a DateTime object

$tomorrow = strtotime('tomorrow 8am');
$nextday = new DateTime();
$nextday->setTimestamp($tomorrow);
echo("<p>\$nextday = " . $nextday->format('m/d/Y h:m a') . "</p>\n");

$nextday = 06/19/2025 08:06 am

Back