Home >Backend Development >PHP Problem >How to get the date and week of the last few days in php
In PHP, getting the date and week of the last few days is not a complicated task and can be easily accomplished using the date function provided by PHP. This article will introduce how to use the date and strtotime functions to get the date and week of the last few days.
1. Get the current date and weekday
Getting the current date and weekday is the simplest task, just call the date function. Here is the code to get the current date and week:
$date = date('Y年m月d日'); $week = date('l'); echo $date . ' ' . $week;
In the above code, the first parameter of the date function is the date format, which can be changed as needed. The format for getting the day of the week is 'l', which means the complete name of the week (such as Monday, Tuesday, etc.), you can also use 'D' (week abbreviation, such as Mon, Tue, etc.) or 'N' (week of the week in ISO-8601 format numbers, 1 for Monday, 7 for Sunday) instead.
2. Get the date and week of the last few days
If you want to get the date and week of the last few days, you can use the strtotime function to generate a date range, and then combine it with the date function to get the date and week. The following is the code to get the date and week of the last 7 days:
$today = date('Y-m-d'); $weekdays = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); for ($i = 1; $i <= 7; $i++) { $day = strtotime('-' . $i . ' days', strtotime($today)); $date = date('Y年m月d日', $day); $week = $weekdays[date('w', $day)]; echo $date . ' ' . $week . '<br />'; }
In the above code, first get the current date and save it in the $today variable, and then define an array $weekdays containing the name of the week, Then use a for loop to get the dates of the last seven days. In the loop body, use the strtotime function to generate a date based on the current date and the number of loops, and then use the date function to format the date and day of the week.
3. Notes
There are some details that need to be noted in the above code:
4. Summary
This article introduces how to use PHP's date and strtotime functions to obtain the current date and week and the date and week of the last few days. These functions are commonly used tools if you need to handle date and time related tasks. Once you master the basic usage of these functions, you can easily implement various date and time-related logic.
The above is the detailed content of How to get the date and week of the last few days in php. For more information, please follow other related articles on the PHP Chinese website!