What are some common methods for manipulating dates in PHP?
When working with dates in PHP, common methods for manipulating dates include adding or subtracting days, months, or years, formatting dates, comparing dates, and extracting specific date components such as the day, month, or year.
// Example of manipulating dates in PHP
// Adding days to a date
$date = date('Y-m-d');
$new_date = date('Y-m-d', strtotime($date . ' + 7 days'));
// Formatting a date
$formatted_date = date('F j, Y', strtotime($date));
// Comparing two dates
$date1 = '2022-01-01';
$date2 = '2022-01-15';
if (strtotime($date1) < strtotime($date2)) {
echo 'Date 1 is before Date 2';
}
// Extracting date components
$day = date('d', strtotime($date));
$month = date('m', strtotime($date));
$year = date('Y', strtotime($date));