2014-06-23 44 views
2

我一直在試圖讓下面的代碼工作,而它與6月一起工作,它不會與7月份。在PHP中獲取給定月份的第一天?

對於$ first_day_of_month,下面的結果值爲3,對於星期二它應該是2。

$date = strtotime('20140702'); // July 02, 2014 
$month = date('m',$date); 
$year = date('Y',$date); 
$days_in_month = date('t',$date); 
$first_day_of_month = date('w', strtotime($year . $month . 01)); // sunday = 0, saturday = 6 
+0

可能需要刪除行「$ days_in_month =日期( 'T',$日期);」因爲它與你的問題無關。 –

回答

5

strtotime功能支持relative time formats。你可以做這個:

$date = strtotime('20140702'); 
$first_date = strtotime('first day of this month', $date); 
$first_day_of_month = date('w', $first_date); 

的第二個參數strtotime提供了相對格式將是相對時間。您可以使用它來輕鬆計算相對於特定點的日期,如上所示。

+0

我有'mm.YYY'等格式,例如:'07.2017',我需要找到本月的第一個和最後一個日期。請考慮這個問題 - @ Alexis King – ubm

2

你將不得不投01爲一個字符串,否則PHP將計算時間2014071,而20140701

strtotime($year . $month . '01') 
0

你應該看看mktime()

在你的情況你最好的辦法是:

$date = strtotime('20140702'); // July 02, 2014 
$month = date('m',$date); 
$year = date('Y',$date); 
$days_in_month = date('t',$date); 


$first_day_of_month = date('w', mktime(0,0,0,$month,1,$year)); // sunday = 0, saturday = 6 

作爲獎勵,你還可以得到每月的最後一天

$last_date_of_month = mktime(0,0,0,$month+1,0,$year); 
相關問題