dongyan2469 2019-04-14 23:55
浏览 13
已采纳

如何使用日期获取PHP中的当天名称?

Is it possible to get the name of the day in the row of numbers converted to date?

I Have Code :

$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));

for($Date = 1; $Date <= $Maximum_Date; $Date++){
  $DataDate = $Date . ' ' . $Month . ' ' . $Year . '<BR>';
  echo $DataDate;
}

Result :

1 04 2019
2 04 2019
3 04 2019
etc..

What I want is to change it to display the name of the day on that date

For Example Date in April :

Monday, 1 04 2019
Tuesday, 2 04 2019
Wednesday, 3 04 2019
etc..

[UPDATE] April 15, 2019 Refer to comments, I see documentation here and apply with mktime();

So I Update The Code :

$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));

for($Date = 1; $Date <= $Maximum_Date; $Date++){
  echo date("l, d m Y", mktime(0, 0, 0, $Month, $Date, $Year)) . '<br>';
}

And get the result :

Monday, 1 04 2019
Tuesday, 2 04 2019
Wednesday, 3 04 2019
etc..

展开全部

  • 写回答

5条回答 默认 最新

  • doskmc7870 2019-04-15 00:39
    关注

    You can simplify this a lot without converting back and forth between date and strtotime:

    $year = date('Y');
    $month = date('n');
    $lastDay = date('t');
    
    foreach (range(1, $lastDay) as $day) {
        echo date('D, j m Y', mktime(0, 0, 0, $month, $day, $year)), '<br>';
    }
    

    See http://php.net/mktime.

    Omitting implicit default values and condensing it a bit, you can in fact boil it down to:

    foreach (range(1, date('t')) as $day) {
        echo date('D, j m Y', mktime(0, 0, 0, date('n'), $day)), '<br>';
    }
    
    Mon, 1 04 2019
    Tue, 2 04 2019
    Wed, 3 04 2019
    ...
    Tue, 30 04 2019
    

    Note that this code has a minuscule potential to break, should you execute it right at the second in which one month rolls over to the next, and the date('n') and date('t') functions happen to be called "in different months". To avoid that possibility entirely, make this operation atomic:

    list($year, $month, $lastDay) = explode(' ', date('Y n t'));
    
    foreach (range(1, $lastDay) as $day) {
        echo date('D, j m Y', mktime(0, 0, 0, $month, $day, $year)), '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部