PHP's date() function formats a date and can return information about the day of the week. Using the "l" parameter, you can get the full English name of the weekday, such as Monday, Tuesday, etc. The "N" parameter returns the numeric representation of the weekday, where 1 stands for Monday and 7 for Sunday.
The example below demonstrates how to use date() along with strtotime() to convert a specific date into the numeric weekday, then use a switch statement to output the corresponding weekday name in Chinese:
$date = "2022-01-01"; // Date to check
$day_of_week = date('N', strtotime($date));
switch ($day_of_week) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
}
This code defines the date variable, uses date() to get the weekday number, and then maps that number to the weekday name in Chinese using a switch structure.
Besides date(), the strftime() function can also be used to get the weekday, with support for localization. By setting the locale to Chinese using setlocale(), strftime() returns the full weekday name in Chinese.
Example:
setlocale(LC_TIME, 'zh_CN.UTF-8'); // Set Chinese locale
$date = "2022-01-01"; // Date to check
$day_of_week = strftime('%A', strtotime($date));
echo $day_of_week;
This code sets the locale to Chinese, then uses strftime() combined with strtotime() to get and print the full weekday name in Chinese.
Using the two methods introduced, you can flexibly determine the weekday of any date and display it in Chinese. Choosing the appropriate function according to your project needs can improve code clarity and efficiency. Hope this tutorial provides useful guidance for your PHP date handling.