You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用指定日期格式输出当月奇数日期?PHP代码修改求助

Hey there! Let's fix your code to only output odd dates in the format you want. Here's the modified version with clear explanations of the key changes:

<?php 
$list = array(); 
$month = 3; // Months are 1-based in PHP, so using integer 3 is cleaner than 03
$year = 2018; 

for($d = 1; $d <= 31; $d++) { 
    // Fixed mktime parameters (correct order: hour, minute, second, month, day, year)
    $time = mktime(0, 0, 0, $month, $d, $year); 
    
    // Two checks here: ensure the day is in the target month, AND it's an odd number
    if (date('m', $time) == $month && $d % 2 !== 0) { 
        // Format the date to match "Saturday 10, FEB, 2018"
        $formattedDate = date('l j, M, Y', $time);
        // Convert the month abbreviation to uppercase
        $formattedDate = str_replace(date('M', $time), strtoupper(date('M', $time)), $formattedDate);
        $list[] = $formattedDate;
    } 
} 

echo "<pre>"; 
print_r($list); 
echo "</pre>"; 
?>

Key Changes Explained:

  • Odd Day Filter: Added $d % 2 !== 0 to the condition. The modulus operator (%) returns the remainder when dividing by 2—if it's not zero, the day is odd, so we include it.
  • Fixed Timestamp Generation: Your original mktime call had the year in the wrong position (it should be the last parameter), which could lead to incorrect dates. I adjusted it to use the standard order: hour, minute, second, month, day, year.
  • Matching Date Format: Switched to l j, M, Y to get the exact structure you requested:
    • l = Full weekday name (e.g., Saturday)
    • j = Day of the month without leading zeros (e.g., 10)
    • M = Three-letter month abbreviation (e.g., Feb)
  • Uppercase Month: Used strtoupper() to convert the month abbreviation to uppercase (FEB) to match your desired output format.

Sample output snippet for March 2018 will look like this:

Array
(
    [0] => Thursday 1, MAR, 2018
    [1] => Saturday 3, MAR, 2018
    [2] => Monday 5, MAR, 2018
    ...
)

内容的提问来源于stack exchange,提问作者Amit Paple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:30:14