As you will notice in this article, it's very easy to work with the dates in the PHP. You may obtain both the server and request times in a single line of code and customize the date strings according to your needs by using the formatting options.
To get the current local date or time, you need to call the date() function and pass a string with the specification of how both the date and time should be formatted. You can see the example below:
<?php
$currentDateAndTime = date('Y-m-d H:i:s');
echo 'System date: ' . $currentDateAndTime;
?>
Description of the date() function is provided below:
date(string $format, int|null $timestamp = null): string
In the above definition, you may see that there is also a second parameter, which is a timestamp of a date to format. If no argument is provided, then the date() function uses the current timestamp of the system.
In our example below, we call the time() function to obtain a timestamp and pass it to the date() function. Although, you can modify that code and provide any value that you wish.
<?php
$customDateAndTime = date('Y-m-d H:i:s', time());
echo 'System date: ' . $customDateAndTime;
?>
It's important to note that you can also configure the timezone by using the date_default_timezone_set() function, since it affects the value formatted by the date() function.
The following code demonstrates how this can be done, we set the "America/Phoenix" timezone in our demo.
<?php
date_default_timezone_set('America/Phoenix');
$currentDateAndTime = date('Y-m-d H:i:s');
echo 'System date: ' . $currentDateAndTime;
?>
Optionally, you can check which timezone is set by default in your system, for that, you should use the date_default_timezone_get() function, it will return the timezone in a string format, please see example of the relevant code below.
<?php
$defaultTimezone = date_default_timezone_get();
echo 'Timezone is: ' . $defaultTimezone;
?>
Format of the date and time string
The following table contains descriptions of all the format modifiers that can be used to configure the output of the date() function.
Time Format
a | am or pm specification |
A | AM or PM specification |
B | Will generate Swatch Internet time, which is 000 through 999 |
g | Will output hour in 12-hour numeric format, which is 1 through 12 |
G | Will output hour in 24-hour numeric format, which is 0 through 23 |
h | Will output zero padded hour in 12-hour numeric format, which is 01 through 12 |
H | Will output zero padded hour in 12-hour numeric format, which is 00 through 23 |
i | Zero padded minutes in a numeric format, which is 00 to 59 |
s | Zero padded seconds in a numeric format, which is 00 through 59 |
Day Format
d | Zero padded day of the month in 2-digit numeric format, for example, 01 to 31 |
D | Day in text format, but this is short version with only three letters, which is Mon through Sun |
j | Day of the month in a numeric format with no leading zero added, for example, 1 to 31 |
l | Full name of the day of the week, which is Sunday through Saturday |
N | Day of the week in accordance to the ISO-8601 specification, which is 1 (for Monday) through 7 (for Sunday) |
S | This is a suffix for the day of the month, like "st", "nd", "rd" or "th". |
w | Day of the week, but starting at zero number, which is 0 (for Sunday) through 6 (for Saturday) |
z | Day of the year, which is 0 through 365 |
Week Format
W | Will return week number of the year, which is compliant to the ISO-8601 standard and starts on Monday, like 35 (the 35nd week in the given year) |
Month Format
F | Will return month of the year, which is January through December |
m | Zero padded month of the year, but in a numeric format, as example, 01 through 12 |
M | Short name of the month, but only three letters are included in the result string, as example, Jan through Dec |
n | Month of the year in a numeric format, with no leading zero added, 1 through 12 |
t | Number of days in the specified month, which is 28 through 31 |
Year Format
L | Will return 1 if it's a leap year, or 0 if not. |
o | Number of the year, which is compliant to the ISO-8601 standard, it means that if the week is in the the previous or next year, that year number will be printed. |
Y | Year in 4-digit numeric format, like 1999, 2015, or 2021 and so on. |
y | Year in 2-digit numeric format, like 99, 05, 10, 20, etc. |
Timezone Format
e | Timezone in a string format, for example, UTC, GMT, or Atlantic/Azores, etc. |
I | Will return 1 if it's daylight saving time, or 0 if not. |
O | Will return difference to GMT, but the result string will not contain the colon symbol inside, like the following: +0200 |
P | Will return difference to GMT, but string will have the colon symbol inside, like the following: +02:00 |
p | This symbol will do the same as the P formatting option, but it returns Z instead of +00:00, for example, +02:00 |
T | This is timezone abbreviation in a string format, for example, MDT, EST |
Z | Will return timezone offset in seconds relative to the UTC, for example, -28800 for the west, and 36000 for the east of UTC. |
Predefined Date or Time Formats
c | Date and time in accordance to the ISO 8601 format, like the following: 2021-07-11T14:12:32+00:00 |
r | Date and time in accordance to the RFC 2822 format, like the following: Wed, 17 Dec 2020 15:23:17 +0300 |
U | Will return seconds passed since the Unix Epoch started. It will be difference between current time on the system and 00:00:00 UTC on 1 January 1970 |
Unix timestamp
Timestamp is the number of seconds passed since the Unix Epoch (January 1 1970 00:00:00 GMT). You can easily obtain this value by calling the time() function as it's shown below:
<?php
echo 'Timestamp: ' . time();
?>
Timestamp of the request to the server
Current system time may differ from the request time, since your code may be executed with some delay. As a result, to detect when exactly the request was made to the server, you need to get a timestamp from the $_SERVER['REQUEST_TIME'] variable and format it according to your needs. You can see how to implement such a functionality in our code sample below:
<?php
$customDateAndTime = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
echo 'Request date: ' . $customDateAndTime;
?>
DateTime class
In previous sections of this article, we described how to call standard PHP functions to get and format current date or time, but there is also an object-oriented approach that you can use in your application to obtain and manipulate dates.
The following example shows how to instantiate an object from the DateTime class and then retrieve the current date and time according to the specified formatting string.
<?php
$customDateAndTime = new DateTime();
echo 'Formatted date: ' . $customDateAndTime->format('Y-m-d H:i:s');
?>
The format() method is very simple, it accepts only one parameter, which is the specification of the date or time. The full list of available formatting characters is provided in the previous section of this article, those options are the same for both functional and object-oriented programming approaches.
Following is the description of the default constructor of the DateTime class, as you see, it accepts two arguments, the datetime and timezone. It is worth mentioning that if no arguments are given, then the current time will be stored in the instantiated object.
public __construct(string $datetime = "now", DateTimeZone|null $timezone = null)
You can change the default time zone with help of the setTimezone() method, but you will need to create an additional object from the DateTimeZone class and pass the timezone name into it's constructor. Please see how this can be done in the following sample.
<?php
$customDateAndTime = new DateTime();
$customDateAndTime->setTimezone(new DateTimeZone('America/Phoenix'));
echo 'Formatted date: ' . $customDateAndTime->format('Y-m-d H:i:s');
?>
It's important to note that the DateTime class also allows you to obtain a timestamp of the date stored in the object, for that, you need to call the getTimestamp() method.
<?php
$customDateAndTime = new DateTime();
echo 'Timestamp: ' . $customDateAndTime->getTimestamp();
?>
Conclusion
After reading and studying this article, you should be able to get the current date or time in PHP and format the time string according to your needs.
As you probably have noticed, the PHP provides very convenient methods. Both object-oriented and functional approaches are suitable for retrieving local time. Which solution to use in your code, is a matter of choice.
For complex web applications, very likely, you may wish to use the DateTime class. But for simple PHP scripts or one-page web sites, the standard date() function will work fine as well.
Comments