简体   繁体   中英

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. The code I have below is how I am attempting to achieve this. For the current year (2018) this works as normal. For example This month is august and the starting weekday is a Wednesday so it will return a 3 for Wednesday. (It works so far)

As we advance the year to 2019 it starts to get the starting weekday wrong. For example January 2019 starts on a Tuesday so it should return 2 but returns 1. (one day out)

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. 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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