This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
You'll often want to work with dates and times when developing websites. For example, you might need to show the last modified date on a post or mention how long ago a reader wrote some comment. You might also have to show a countdown of the days until a special event.
Luckily, PHP comes with some built-in date and time functions which will help us do all that and much more quite easily.
This tutorial will teach you how to format the current date and time in PHP. You will also learn how to get the timestamp from a date string and how to add and subtract different dates.
Getting the Date and Time in String Format
date($format, $timestamp)
is one of the most commonly used date and time functions available in PHP. It takes the desired output format for the date as the first parameter and an integer as a timestamp value which needs to be converted to the given date format. The second parameter is optional, and omitting it will output the current date and time in string format based on the value of $format
.
The $format
parameter accepts a series of characters as valid values. Some of these characters have straightforward meanings: Y
gives you the full numeric representation of the year with 4 digits (2018), and y
only gives you the last two digits of the current year (18). Similarly, H
will give you the hour in 24-hour format with leading zeros, but h
will give you the hour in 12-hour format with leading zeros.
Here are some of the most common date format characters and their values.
Character | Meaning | Example |
---|---|---|
d |
day of the month with leading zeros | 03 or 17 |
j |
day of the month without leading zeros | 3 or 17 |
D |
day of the week as a three-letter abbreviation | Mon |
l |
full day of the week | Monday |
m |
month as a number with leading zeros | 09 or 12 |
n |
month as a number without leading zeros | 9 or 12 |
M |
month as a three-letter abbreviation | Sep |
F |
full month | September |
y |
two-digit year | 18 |
Y |
full year | 2018 |
There are many other special characters to specify the output for the date()
function. It is best to consult the format characters table in the date()
function documentation for more information about special cases.
Let's see some practical examples of the date()
function now. We can use it to get the current year, current month, current hour, etc., or we can use it to get a complete date string.
<?php // Output — 2018 echo date('Y'); // Output — September 2018 echo date('F Y'); // Output — 13 September, 2018 echo date('d F, Y'); // Output — 13 September, 2018 (Thursday) echo date('d F, Y (l)');
You can also use the date()
function to output the time. Here are some of the most commonly used time format characters:
Character | Meaning | Example |
---|---|---|
g |
hours in 12-hour format without leading zeros | 1 or 12 |
h |
hours in 12-hour format with leading zeros | 01 or 12 |
G |
hours in 24-hour format without leading zeros | 1 or 13 |
H |
hours in 24-hour format with leading zeros | 01 or 13 |
a |
am/pm in lowercase | am |
A |
am/pm in uppercase | AM |
i |
minutes with leading zeros | 09 or 15 |
s |
seconds with leading zeros | 05 or 30 |
And here are some examples of outputting formatted time strings.
// Output — 11:03:37 AM echo date('h:i:s A'); // Output — Thursday, 11:04:09 AM echo date('l, h:i:s A'); // Output — 13 September 2018, 11:05:00 AM echo date('d F Y, h:i:s A'); ?>
It is also important that you escape these special characters if you want to use them inside your date string.
<?php // Output — CEST201813am18 1115 Thursday. echo date('Today is l.'); // Output — Today is Thursday. echo date('\T\o\d\a\y \i\s l.'); // Output — Today is Thursday. echo 'Today is '.date('l.'); ?>
Get the Unix Timestamp
Sometimes, you will need to get the value of the current Unix timestamp in PHP. This is very easy with the help of the time()
function. It returns an integer value which describes the number of milliseconds that have passed since 1 January 1970 at midnight (00:00:00) GMT.
You can also use this function to go back and forth in time. To do so, all you have to do is subtract the right number of seconds from the current value of time()
and then change the resulting value into the desired date string. Here are two examples:
<?php $ten_days_later = time() + 10*60*60*24; // Output — It will be Sunday 10 days later. echo 'It will be '.date('l', $ten_days_later).' 10 days later.'; $ten_days_ago = time() - 10*60*60*24; // Output — It was Monday 10 days ago. echo 'It was '.date('l', $ten_days_ago).' 10 days ago.'; ?>
One important thing you should remember is that the timestamp value returned by time()
is time-zone agnostic and gets the number of seconds since 1 January 1970 at 00:00:00 UTC. This means that at a particular point in time, this function will return the same value in the US, Europe, India, or Japan.
Another way to get the timestamp for a particular date would be to use the mktime($hour, $minute, $second, $month, $day, $year)
function. When all the parameters are omitted, this function just uses the current local date and time to calculate the timestamp value. This function can also be used with date()
to generate useful date and time strings.
<?php $some_time = mktime(1, 1, 1, 12, 3, 1994); // Output — It was Saturday on 03 December, 1994. echo 'It was '.date('l', $some_time).' on '.date('d F, Y', $some_time).'.'; ?>
Basically, time()
can be used to go back and forth to a period of time, while mktime()
is useful when you want to go to a particular point in time.
Convert a Datetime String to a Timestamp
The strtotime($time, [$now = time()])
function will be incredibly helpful when you want to convert different date and time values in string format to a timestamp. The function can parse almost all kinds of datetime strings into timestamps.
You should definitely check the valid time formats, date formats, compound datetime formats, and relative datetime formats.
With relative datetime formats, this function can easily convert commonly used strings into valid timestamp values. The following examples should make it clear:
<?php $some_time = strtotime("10 months 15 days 10 hours ago"); // Output — It was Sunday on 29 October, 2017 03:16:46. echo 'It was '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.'; $some_time = strtotime("next month"); // Output — It is Saturday on 13 October, 2018 01:18:05. echo 'It is '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.'; $some_time = strtotime("third monday"); // Output — Date on the third monday from now will be 01 October, 2018. echo 'Date on the third monday from now will be '.date('d F, Y', $some_time).'.'; $some_time = strtotime("last day of November 2021"); // Output — Last day of November 2021 will be Tuesday. echo 'Last day of November 2021 will be '.date('l', $some_time).'.'; ?>
Adding, Subtracting, and Comparing Dates
It's possible to add and subtract specific periods of time to and from a date. This can be done with the help of the date_add()
and date_sub()
functions. You can also use the date_diff()
function to subtract two dates and output the difference between them in terms of years, months, and days, or something else.
Generally, it's easier to do any such date and time related arithmetic in object-oriented style with the DateTime
class instead of doing it procedurally. We'll try both these styles here, and you can choose whichever you like the most.
<?php $present = date_create('now'); $future = date_create('last day of January 2024'); $interval = date_diff($present, $future); // Output — 05 years, 04 months and 17 days echo $interval->format('%Y years, %M months and %d days'); $present = new DateTime('now'); $future = new DateTime('last day of January 2024'); $interval = $present->diff($future); // Output — 05 years, 04 months and 17 days echo $interval->format('%Y years, %M months and %d days'); ?>
When using DateTime::diff()
, the DateTime
object on which the diff()
method is called is subtracted from the DateTime
object which is passed to the diff()
method. When you are writing procedural style code, the first date parameter is subtracted from the second date parameter.
Both the function and the method return a DateInterval()
object representing the difference between two dates. This interval can be formatted to give a specific output using all the characters listed in the format()
method documentation.
The difference between object-oriented style and procedural style becomes more obvious when subtracting or adding a time interval.
You can instantiate a new DateTime
object using the DateTime()
constructor. Similarly, you can instantiate a DateInterval
object using the DateInterval()
constructor. It accepts a string as its parameter. The interval string starts with P
, which signifies period. After that, you can specify each period using an integer value and the character assigned to a particular period. You should check the DateInterval
documentation for more details.
Here is an example that illustrates how easy it is to add or subtract dates and times in PHP.
<?php $now = new DateTime('now'); $the_interval = new DateInterval('P20Y5M20D'); $now->add($the_interval); // Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today. echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.'; $now = date_create('now'); $the_interval = date_interval_create_from_date_string('20 years 05 months 20 days'); date_add($now, $the_interval); // Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today. echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.'; ?>
You can also compare dates in PHP using comparison operators. This can come in handy every now and then. Let's create a Christmas day counter using the comparison operators and other DateTime
methods.
<?php $now = new DateTime('today'); $christmas = new DateTime('25 December 2018'); while($now > $christmas) { $christmas->add(new DateInterval('P1Y')); } if($now < $christmas) { $interval = $now->diff($christmas); echo $interval->format('%a days').' until Christmas!'; } if($now == $christmas) { echo 'Merry Christmas :)'; } // Output — 103 days until Christmas! ?>
We began by creating two DateTime
objects to store the present time and the date of this year's Christmas. After that, we run a while
loop to keep adding 1 year to the Christmas date of 2018 until the present date is less than the Christmas date. This will be helpful when the code runs on 18 January 2024. The while loop will increment the Christmas date as long as it is less than the present date at the time of running this script.
Our Christmas day counter will now work for decades to come without any problems.
Frequently Asked Questions About date()
in PHP
There are some common questions about getting different kinds of information from the date()
function in PHP that pop up every now and then. We will try to answer all of them here.
How Do I Get the Current Year in PHP?
You can get the current year in PHP by using date('y')
or date('Y')
. Using a capital Y will give you all the digits of the current year, like 2021. Using the small y will only give you the last two digits, like 21.
<?php echo date('Y'); // 2021 echo date('y'); // 21 ?>
What Is the Right Way to Get the Current Month in PHP?
There are four different characters for getting the current month in PHP, depending on the format you want. You can use the capital letter F to get the full name of the month, like February, or get the month in a shorter three-letter format by using M.
You can also get the current month in numerical terms by using m and n, which will give you the month with and without leading zeroes respectively.
<?php echo date('F'); // February echo date('M'); // Feb echo date('m'); // 02 echo date('n'); // 2 ?>
How Can I Get the Day of the Week in PHP?
You can also get the day of the week in PHP by using four different characters. The capital D will give you a three-letter representation of the day of the week, like Mon or Tue. Using an l (lowercase L) will give you the full name of the day of the week.
You can get a numerical value between 0 (for Sunday) and 6 (for Saturday) for the days of a week by using w.
<?php echo date('D'); // Fri echo date('l'); // Friday ?>
How Do I Get the Current Time in 12-Hour Format in PHP?
You can get the current time of the day in a 12-hour format by using g or h. With g, you will get the time without any leading zeroes, while h will add some leading zeroes. The AM or PM can be added by using a (for small letters) or A (for capital letters).
<?php echo date('g:i:s a'); // 5:05:19 am echo date('h:i:s A'); // 05:05:19 AM ?>
Can I Get the Current Time in 24-Hour Format in PHP?
Using the characters G and H will give you the current hour of the day in 24-hour format. You won't get any leading zeroes with G, but H will add leading zeroes.
<?php echo date('G:i:s'); // 15:06:48 ?>
What Is the Best Way to Escape Characters in a Date Format?
The date()
function accepts a string as its parameter, but many characters have a well-defined meaning, like Y for year and F for a month. This means that using these characters directly as part of a string may not always have the desired results.
If you want the date()
function to output these characters, then you have to escape them first. Here is an example:
<?php echo 'Today is '.date("l the jS of F Y"); // Today is Friday 2804Europe/Berlin 19th 2021f February 2021 echo 'Today is '.date("l \\t\h\\e jS \of F Y"); // Today is Friday the 19th of February 2021 ?>
Some of the characters, like t, need two backslashes because \t is meant for tabs. If possible, it is advisable to just put the regular string that you want to echo outside date()
. Otherwise, you will be escaping a lot of characters.
Final Thoughts
In this tutorial, we learned how to output the current date and time in a desired format using the date()
function. We also saw that date()
can also be used to get only the current year, month, and so on. After that, we learned how to get the current timestamp or convert a valid DateTime
string into a timestamp. Finally, we learned how to add or subtract a period of time from different dates.
I've tried to cover the key DateTime
functions and methods here. You should definitely take a look at the documentation to read about the functions not covered in the tutorial. If you have any questions, feel free to let me know in the comments.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Monty Shokeen | Sciencx (2021-02-26T17:23:22+00:00) Formatting the Current Date and Time in PHP. Retrieved from https://www.scien.cx/2021/02/26/formatting-the-current-date-and-time-in-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.