PHP provides powerful tools for date arithmetic, and the primary class responsible for this is the `DateTime` class. Along with that, there's a procedural style using the `date()` function and related functions. Let's break down the core aspects:
Procedural Style:
echo date("Y-m-d H:i:s");
Object-Oriented Style:
$now = new DateTime();
echo $now->format("Y-m-d H:i:s");
You can format the date output using various format characters. Procedural Style:
echo date("l, d M Y");
This will output something like "Sunday, 19 Sep 2023". Object-Oriented Style:
$date = new DateTime();
echo $date->format("l, d M Y");
You can create a `DateTime` object from a string.
$date = DateTime::createFromFormat("Y-m-d", "2023-09-19");
echo $date->format("l, d M Y");
Add/Subtract:
$date = new DateTime();
$date->add(new DateInterval('P10D')); // adds 10 days
$date->sub(new DateInterval('P1Y')); // subtracts 1 year
echo $date->format("Y-m-d");
$datetime1 = new DateTime("2023-01-01");
$datetime2 = new DateTime("2023-09-19");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
This would output "+261 days".
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime('now', $timezone);
echo $date->format('Y-m-d H:i:s');
Convert `DateTime` to timestamp and vice-versa. DateTime to Timestamp:
$date = new DateTime();
$timestamp = $date->getTimestamp();
Timestamp to DateTime:
$timestamp = time();
$date = DateTime::createFromFormat('U', $timestamp);
$date = new DateTime();
$date->modify('+1 day');
echo $date->format('Y-m-d');
$datetime1 = new DateTime("2023-01-01");
$datetime2 = new DateTime("2023-09-19");
if ($datetime1 < $datetime2) {
echo "January 1, 2023 is before September 19, 2023";
}
$is_valid = checkdate(12, 31, 2023); // for December 31, 2023
if ($is_valid) {
echo "The date is valid!";
} else {
echo "The date is not valid!";
}
These are some of the primary aspects of working with dates in PHP. There's more, especially when you start looking into more complex date manipulations and integrations with other parts of PHP (like databases), but this should give you a solid start.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here