简体   繁体   中英

How to determine if day of week is 1st, 2nd, 3rd, etc occurrence in a month?

I need to determine what day of the week a given date is, and what occurrence of that day of week it is in the given date's month.

The 3rd Sunday in January, 2017 is the 15th. I know this by looking at a calendar. But given I only know the exact date, how can I figure out it's the 3rd Sunday programmatically?

Determining the actually day of week is pretty easy by loading the date into PHP and formatting it to output the day:

$day_of_week = date('l', $timestamp);

It's the other part I can't quite figure out.

Try this which works out the current day or you could set any other valid timestamp to $timestamp:

<?php
date_default_timezone_set('UTC');
$timestamp = time();
$day_of_week = date('l', $timestamp);
$day_of_the_month = date('j', $timestamp);
$occurence = ceil($day_of_the_month / 7);
$suffix = 'th';

if($occurence == 3){
  $suffix = 'rd';
} else if($occurence == 2){
  $suffix = 'nd';
} else if($occurence == 1){
  $suffix = 'st';
}

print 'It is the '.$occurence.$suffix.' '.$day_of_week.' of this month';
?>

I see no better way than just looping throught the full month and counting which on them is sunday. I would also recommend you to use a library like Carbon ( Carbon oficial docs )

So, your code should be doing:

  1. You collect you date

 $dt = Carbon::createFromDate(2012, 10, 6); 

  1. A Carbon date object has a property called "dayOfWeek", so no more hassle here

 if ($dt->dayOfWeek === Carbon::SATURDAY) { } 

  1. @CBroe is actually better. You can just just divide by 7 your week number (no decimals) and add 1 to the result, that's the ocurrence.

PD: Sorry, I got no PHP editor nor access to my development PC

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