简体   繁体   English

如何使用PHP中的date()获得未来一年中一个月的开始工作日

[英]How to get the starting weekday of a month in a future year using date() in php

I am using a date() format to return the starting weekday of a month. 我正在使用date()格式返回一个月的开始工作日。 The code I have below is how I am attempting to achieve this. 我下面的代码是我试图实现这一目标的方式。 For the current year (2018) this works as normal. 对于本年度(2018年),此操作正常。 For example This month is august and the starting weekday is a Wednesday so it will return a 3 for Wednesday. 例如,本月是八月,开始的工作日是星期三,因此它将为星期三返回3。 (It works so far) (到目前为止有效)

As we advance the year to 2019 it starts to get the starting weekday wrong. 当我们将这一年提前到2019年时,它就会开始错误地开始工作日。 For example January 2019 starts on a Tuesday so it should return 2 but returns 1. (one day out) 例如,2019年1月在星期二开始,因此应该返回2但返回1。

This error seems to be cumulative so if we go to 2020 then it is 2 days out etc. I have tried so hard to format this Date() correctly but to no avail. 该错误似乎是累积性的,所以如果我们到2020年,则要等2天,等等。我已经尽力尝试正确格式化此Date(),但无济于事。 Is this even the correct way to do this? 这甚至是正确的方法吗?

Code: 码:

$future_month = 5 /*for January 2019*/     
$starting_weekday = date('N',mktime(0, 0, 0, date('m', strtotime('+'.$future_month.' months', strtotime(date('Y-m-01')))), 1));

Many Thanks 非常感谢

Cameron 卡梅伦

Your code makes this much more complicated than it needs to be. 您的代码使事情变得复杂得多。

$dt = new DateTime('first day of +5 months')
$dt->format('N'); // "2"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM