To calculate the day of the year for a given date using DateTime in PHP, you can use the following steps:
Create a new instance of the DateTime class, passing the given date as a parameter in the format "YYYY-MM-DD".
$date = new DateTime('2022-07-15');
Use the format() method of the DateTime object with the 'z' format specifier to get the day of the year (ordinal date).
$dayOfYear = $date->format('z') + 1;
The 'z' format specifier returns the day of the year starting from 0, so you need to add 1 to get the ordinal date.
You can then echo or use the $dayOfYear variable as per your requirement.
echo "The day of the year is: " . $dayOfYear;
Here is the complete code:
$date = new DateTime('2022-07-15');
$dayOfYear = $date->format('z') + 1;
echo "The day of the year is: " . $dayOfYear;
This code will output: "The day of the year is: 196" for the given date "2022-07-15".