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 give 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.
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.
by Monty Shokeen via Envato Tuts+ Code
No comments:
Post a Comment