When it comes to working with dates in PHP, there are a lot of different functions and techniques you can use. In this beginner's guide, we'll take a closer look at some of the most essential ones.
Throughout the guide, we'll provide plenty of code examples and step-by-step instructions to help you master these essential skills. By the end of the tutorial, you'll have a solid understanding of how to work with dates in PHP and be able to apply these techniques to your own web development projects.
Here's an example code for adding or subtracting days, months, and years, and finding the first or last day of a month in PHP:
// Add or subtract days, months, and years $date = date('Y-m-d'); // Current date $daysToAdd = 7; $monthsToAdd = 3; $yearsToAdd = 2; $newDate = strtotime("+$daysToAdd days", strtotime($date)); // Add days $newDate = strtotime("+$monthsToAdd months", $newDate); // Add months $newDate = strtotime("+$yearsToAdd years", $newDate); // Add years $newDate = date('Y-m-d', $newDate); // Format date echo $newDate; // Output: 2025-06-20 // Find first and last day of a month $month = 3; $year = 2023; $firstDayOfMonth = date('Y-m-01', strtotime("$year-$month-01")); // First day of month $lastDayOfMonth = date('Y-m-t', strtotime("$year-$month-01")); // Last day of month echo $firstDayOfMonth; // Output: 2023-03-01 echo $lastDayOfMonth; // Output: 2023-03-31
This code shows how to use the strtotime function to add or subtract days, months, and years from a given date, and the date function to format the resulting date. It also demonstrates how to find the first and last day of a month using the date function and some basic arithmetic.