DateTime   PHP


Summary

usage of the DateTime class.


Requirements

PHP 5 >= 5.2.0, PHP 7


<?php
echo '<pre>';

// date_default_timezone_set('Asia/Seoul'); // set default timezone

$current = new DateTime();
$current_us = new DateTime("now", new DateTimeZone("US/Eastern"));

echo $current->format('Y-m-d H:i:s') . PHP_EOL;

$ago_2mins = new DateTime('-2 minutes');
echo $ago_2mins->format('Y-m-d H:i:s') . PHP_EOL;

$yesterday = new DateTime('yesterday');
echo $yesterday->format('Y-m-d H:i:s') . PHP_EOL;

if($current > $ago_2mins) {
    echo 'ok' . PHP_EOL;
} else {
    echo 'wrong' . PHP_EOL;
}

$after_7days = clone $current; // deep copy
$after_7days->add(date_interval_create_from_date_string('7days')); // or new DateInterval('P7D')

echo $after_7days->format('Y-m-d H:i:s') . PHP_EOL;
echo $current->format('Y-m-d H:i:s') . PHP_EOL;

echo '</pre>';


Result

2019-07-30 03:54:40
2019-07-30 03:52:40
2019-07-29 12:00:00
ok
2019-08-06 03:54:40
2019-07-30 03:54:40

References


Tags

#dateinterval  #datetime 


[ Edit (Author only) ]