Skip to content

Instantly share code, notes, and snippets.

@johnmorris
Created November 20, 2015 00:01
Show Gist options
  • Save johnmorris/23cbc385f8a3f32f8533 to your computer and use it in GitHub Desktop.
Save johnmorris/23cbc385f8a3f32f8533 to your computer and use it in GitHub Desktop.
How to Use the PHP DateTime Class Instead of the PHP Date Function
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Manipulating PHP DateTime</title>
</head>
<body>
<h1>Working With DateTime Extension (PHP 5.2+)</h1>
<h4>Defaults to the time now and is an object:</h4>
<?php $date = new DateTime(); print_r($date); ?><br>
<?php echo $date->date; ?><br>
<?php echo $date->getTimestamp(); ?>
<h4>Set a specific date using various formats:</h4>
<?php $date = new DateTime('tomorrow'); print_r($date); ?><br>
<?php $date = new DateTime('March 24, 2013'); print_r($date); ?>
<h4>Compare dates directly:</h4>
<?php
$one = new DateTime('tomorrow');
$two = new DateTime('March 24, 2013');
if ( $one > $two ) {
echo 'date one is greater than date two <br>';
}
$diff = $one->diff($two); print_r($diff);
?>
<h4>Working with timezones:</h4>
<?php $date = new DateTime('now', new DateTimeZone('America/Chicago')); print_r($date); ?>
<h4>Using DatePeriod:</h4>
<?php $period = new DatePeriod($two, new DateInterval('P3D'), $one);
foreach ( $period as $datetime ) {
printf('<li>%s</li>', $datetime->format('Y-m-d'));
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment