簡體   English   中英

如何確定星期幾在一個月中的第一,第二,第三等發生?

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

我需要確定給定日期是星期幾,以及給定日期月份是星期幾。

2017年1月的第3個星期日是15號。 我通過看日歷知道這一點。 但是,由於我只知道確切的日期,我如何以編程方式確定它是第三個星期日?

通過將日期加載到PHP中並將其格式化以輸出日期,從而確定實際的星期幾非常容易:

$day_of_week = date('l', $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';
?>

除了循環瀏覽整個月並指望星期幾是一個更好的方法。 我也建議您使用像Carbon這樣的庫( Carbon oficial docs

因此,您的代碼應該這樣做:

  1. 你收集你的日期

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

  1. Carbon日期對象具有名為“ dayOfWeek”的屬性,因此這里不再麻煩

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

  1. @CBroe實際上更好。 您只需將您的周數除以7(無小數),然后將1加到結果中即可。

PD:抱歉,我沒有PHP編輯器,也沒有訪問我的開發PC的權限

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM