Wednesday, September 19, 2018

Formatting the Current Date and Time in PHP

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.

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.

It is also important that you escape these special characters if you want to use them inside your date string.

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:

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.

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:

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.

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.

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.

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