From accurately tracking the opening and closing of financial markets to preserving the history of posts and research papers by properly saving the times they were created, edited, and deleted, software engineers must understand how to handle dates and times in their applications. The concept of dates and times is especially important in programming. All programming languages enable developers to manage dates and times in their applications. In this article, you will learn everything you need to know about PHP dates and times and how to use them effectively in your applications.
Prerequisites
To follow along with this tutorial, you will need to understand the basics of PHP. Knowledge of variables, functions, objects, and classes will also be helpful. However, concepts covered in the article will be explained before they are used.
Important: There is a timing flaw in the original date and time functions when used on Windows and specific Unix installations. These functions cannot effectively process dates before December 13, 1901, or after January 19, 2038. This limitation arises from the utilization of a 32-bit signed integer for date and time management. To ensure greater accuracy, it is advised to employ the DateTime class family.
Working with dates in PHP
PHP provides a DateTime class with a rich set of methods for manipulating them. In this section, I will explore these methods and what they enable you to do in your applications.
Parsing dates in PHP
Parsing is the process of converting a string value into a date object. For example, if you get a user’s date of birth from a form on your application, you need to convert the string into a date object that you can use for further processing in your code. Here’s an example:
“`php
$birthday = ‘2002-09-12’;
$date = DateTime::createFromFormat(‘Y-m-d’, $birthday);
echo “Your birthday is on ” . $date->format(‘l, F jS, Y’) . “
“;
“`
The code above defines a birthday variable, representing the value of a birthday field in a form. It uses `createFromFormat` to format it in the year-month-day format using the designated letters. Finally, it prints out a message that looks like the following to the user:
Your birthday is on Sunday, September 3rd, 2002
Understanding format characters
In PHP, you can use various predefined date formats by using format characters with the DateTime class. Here are some commonly used predefined date formats:
– Y – Year with four digits (e.g., “2023”).
– y – Year with two digits (e.g., “23”).
– F – Full month name (e.g., “September”).
– M – Abbreviated month name (e.g., “Sep”).
– m – Month as a zero-padded number (e.g., “09”).
– n – Month as a number without leading zeros (e.g., “9”).
– d – Day of the month as a zero-padded number (e.g., “08”).
– j – Day of the month as a number without leading zeros (e.g., “8”).
– D – Abbreviated day of the week (e.g., “Mon”).
– l – Full day of the week (e.g., “Monday”).
– N – ISO-8601 numeric representation of the day of the week (1 for Monday, 7 for Sunday).
– w – Numeric representation of the day of the week (0 for Sunday, 6 for Saturday).
– W – ISO-8601 week number of the year (e.g., “37”).
– z – Day of the year (0 through 365).
– G – Hour in 24-hour format without leading zeros (e.g., “9” or “23”).
– H – Hour in 24-hour format with leading zeros (e.g., “09” or “23”).
– i – Minutes with leading zeros (e.g., “05”).
– s – Seconds with leading zeros (e.g., “07”).
– a – Lowercase AM or PM (e.g., “am” or “pm”).
– A – Uppercase AM or PM (e.g., “AM” or “PM”).
– U – Unix timestamp (seconds since the Unix epoch).
– S – Adds “nd”, “rd”, “th”, etc. at the end of numeric dates
– r – “-” If the difference is negative; empty if the difference is positive.
– R – “–” If the difference is negative; “+” if the difference is positive.
As shown in the previous code block, these format characters can be combined to create custom date formats according to your specific needs.
Parsing relative dates
PHP enables you to easily parse relative dates, such as tomorrow, next week, the following Monday, etc. using the `strtotime` function or `format` method. Here are some examples:
“`php
$tommorow = ‘tomorrow’;
$date = new DateTime($tommorow);
echo “Tommorow’s date is: ” . $date->format(‘Y-m-d, l’) . “
“;
$nextWeek = strtotime(‘next week’);
echo “Exactly a week from now is: ” . date(‘Y-m-d, l’, $nextWeek) . “
“;
$nextMonth = strtotime(‘next month’);
echo “Next month is: ” . date(‘F Y’, $nextMonth). “
“;
$next2Month = strtotime(‘next 2 months’);
echo “Any unsupported string will return: ” . date(‘F Y’, $next2Month). “
“;
$secondMondayOfNextMonth = strtotime(‘second monday of next month’);
echo “Second Monday of next month is: ” . date(‘l Y-m-d’, $secondMondayOfNextMonth). “
“;
$lastDayNextMonth = strtotime(‘last day of next month’);
echo “Last day of next month is: ” . date(‘l Y-m-d’, $lastDayNextMonth). “
“;
$twoWeeksAgo = strtotime(‘2 weeks ago’);
echo “Exactly 2 weeks from now is: ” . date(‘l Y-m-d’, $twoWeeksAgo). “
“;
$nextMonday = strtotime(‘next monday’);
echo “Next Monday’s date is: ” . date(‘l Y-m-d’, $nextMonday). “
“;
$nextFriday = strtotime(‘next friday’);
echo “Next Friday’s date is: ” . date(‘l Y-m-d’, $nextFriday). “
“;
$twoDaysFromNow = strtotime(‘2 days’);
echo “Exactly 2 days from now is ” . date(‘l Y-m-d H:i:s’, $twoDaysFromNow). “
“;
“`
The code above defines supported strings as variables with the `strtotime` function, which converts them into date objects. The code above should return a result similar to the following depending on when you run the code:
Tomorrow’s date is: 2023-09-13, Wednesday
Exactly a week from now is: 2023-09-18, Monday
Next month is: October 2023
Any unsupported string will return: January 1970
Second Monday of next month is: Monday 2023-10-09
Last day of next month is: Tuesday 2023-10-31
Exactly 2 weeks from now is: Tuesday 2023-08-29
Next Monday’s date is: Monday 2023-09-18
Next Friday’s date is: Friday 2023-09-15
Exactly 2 days from now is Thursday 2023-09-14 15:46:59
Note: Any unsupported string will return a default date of January 1970 00:00:00, depending on how you format the result.
Formatting dates
Formatting dates converts date objects into readable strings that users can understand. Here’s an example:
“`php
$currentDateTime = new DateTime();
echo $currentDateTime->format(‘Y-m-d H:i:s’);
“`
The code above defines a `$currentDate` variable that creates a new date object with the current date and returns the date object in a readable format using some formatting characters covered in the previous section.
Formatting timestamps
Converting timestamps to readable strings is straightforward in PHP thanks to the `
Source link