[英]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. 2017年1月的第3个星期日是15号。 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: 通过将日期加载到PHP中并将其格式化以输出日期,从而确定实际的星期几非常容易:
$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: 尝试使用此方法可以解决当前问题 ,也可以将其他有效时间戳记设置为$ 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 ) 我也建议您使用像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 PD:抱歉,我没有PHP编辑器,也没有访问我的开发PC的权限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.