One of the things most developers face is dealing with time calculations and logging. In this lesson we play around with the DateTime class and see how useful it can be.
We start off with a simple example where we set the $date variable to today's date (Line 3).
We then format the date into the Year-month-day format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$date = new DateTime('today'); | |
echo $date->format('Y-m-d'); | |
// based on today's date the output will be 2016-01-11 |
The nice thing about the DateTime class is that we can also do things like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$date = new DateTime('next Friday'); | |
echo $date->format('Y-m-d'); | |
// based on today's date the output will be 2016-01-15 |
...and this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$date = new DateTime('11th January 1870'); | |
echo $date->format('l'); | |
// output will be: Tuesday |
We can also perform calculations. We have already used this function in this tutorial.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$date1 = new DateTime('11th January 1870'); | |
$date2 = new DateTime('27-12-2032'); | |
$difference = $date1->diff($date2); | |
echo $difference->format('%R%a days'); | |
// output will be +59520 days |