How to print selected number of week in php?

Member

by larissa , in category: PHP General , 10 months ago

How to print selected number of week in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 6 months ago

@larissa 

To print selected number of week in PHP, you can use the date() function along with the "W" format specifier. Here is an example code that prints the current week number:

1
2
$week_number = date('W');
echo "Current week number: " . $week_number;


If you want to print a specific week number, you can use the DateTime class to set a specific date and then retrieve the week number:

1
2
3
$specific_date = '2021-12-25';
$week_number = (new DateTime($specific_date))->format('W');
echo "Week number for date $specific_date: " . $week_number;


You can also use the week number as a parameter in the date() function to get the date range for a specific week:

1
2
3
4
5
6
$week_number = 52; // Change this to the desired week number
$year = date('Y');
$start_date = date("Y-m-d", strtotime("$year-W$week_number-1")); // Get the Monday of the week
$end_date = date("Y-m-d", strtotime("$year-W$week_number-7")); // Get the Sunday of the week

echo "Week $week_number in $year starts on $start_date and ends on $end_date";


These examples demonstrate how you can print the selected number of weeks in PHP.