This post covers the Date and Time section of the Data Formats and Types chapter when studying for the Zend PHP 7 Certification.
Date and time functions retrieve date and time data from the PHP server.
The date()
function formats a local time/date. There are several options of the format you can output. Some of them can be seen below.
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
getdate()
gets date/time information. The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given.
For example, to get today’s date:
<?php
$today = getdate();
print_r($today);
The time()
function returns the current time measured in the number of seconds.
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// Outputs:
Now: 2016-05-08
Next Week: 2016-05-15
The strtotime()
function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC
<?php
echo strtotime("10 September 2000"), "\n";
// Outputs:
968536800
You can also pass a string such as the following examples shown below.
echo strtotime("now"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
The DateTime
class can be used to represent the date and time.
It contains a few methods such setDate()
, which sets the date of a DateTime
object.
<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d'); // Outputs: 2001-02-03
setTime()
sets the time of a DateTime
object.
<?php
$date = new DateTime('2001-01-01');
$date->setTime(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n"; // Outputs: 2001-01-01 14:55:00
The add()
function adds an amount of days, months, years, hours, minutes and seconds to a DateTime
object.
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D')); // 10D means add 10 days
echo $date->format('Y-m-d') . "\n"; // Outputs: 2000-01-11
View the other sections:
Note: This article is based on PHP version 7.0.