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:
$dt = Carbon::createFromDate(2012, 10, 6);
if ($dt->dayOfWeek === Carbon::SATURDAY) { }
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.