简体   繁体   中英

Get previous weekday from sql date string in PHP

I have a date string in sql format (eg 2017-08-05 ) and will like to convert it to get the previous weekday.

I know that there is the strtotime method where I can get the previous weekday from a specific date, such as:

date("Y m d",strtotime("-2 Weekday", strtotime("2017-08-05")));

Is there a better (prettier) way to do this? Or is this the PHP way?

By using Carbon

Carbon::parse('2017-08-05')->previousWeekday()

Or if you want sameway

Carbon::parse('2017-08-05')->subWeekday(2)->toDateString()

只需调用strtotime即可达到相同的目的:

date("Y m d", strtotime("2017-08-05 -2 Weekday"))

Try this:

// create a new instance of DateTimeImmutable
$date = new \DateTimeImmutable('2017-08-05');

// create a one-day interval
$interval = new \DateInterval('P1D');

// subtract the interval, and keep doing that while the day before is not a weekday
do {
    $date = $date->sub($interval);
} while (5 < $date->format('N'));

echo $date->format('Y-m-d');

For reference, see:

For an example, see:

you can create a carbon

carbon::parse('2012-08-05')->previousWeekday();

No better way then this...

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