2011-09-24 111 views
43

我希望重寫一個使用month()和year()函數的mysql查詢來顯示某個月的所有帖子,這些帖子會作爲'Ymd '參數格式,但我不知道如何才能得到給定月份日期的最後一天。如何獲取給定月份的第一天和最後一天

$query_date = '2010-02-04'; 
list($y, $m, $d) = explode('-', $query_date); 
$first_day = $y . '-' . $m . '-01'; 

回答

98

你可能想看看strtotimedate功能。

<?php 

$query_date = '2010-02-04'; 

// First day of the month. 
echo date('Y-m-01', strtotime($query_date)); 

// Last day of the month. 
echo date('Y-m-t', strtotime($query_date)); 
+0

ty:你的方法更聰明。不需要爆炸。 –

+0

如果$ query_date來自php的'd-m-Y'格式:'02-04-2010'怎麼辦?在我的測試中,它很好,但也許我沒有測試所有的情況。我是否必須轉換爲Y-m-d或時間,無論如何都要理解它。 –

+0

支持「d-m-Y」格式。支持的格式列於[http://ca2.php.net/manual/en/datetime.formats.date.php](http://ca2.php.net/manual/en/datetime.formats.date。 PHP)。 –

0

基本上是:

$lastDate = date("Y-m-t", strtotime($query_d)); 

日期噸參數迴天數在當月。

4

cal_days_in_month()應該給你一個月的總天數,因此,最後一天。

+0

感謝您的分享。我從來沒有使用過日曆PHP模塊。有鑑於此,值得指出的是,模塊*可能不會被安裝,尤其是在共享主機上。 –

5

我知道這個問題用't'有個很好的答案,但我認爲我會添加另一個解決方案。

$first = date("Y-m-d", strtotime("first day of this month")); 
$last = date("Y-m-d", strtotime("last day of this month")); 
6

試試這個,如果你使用的是PHP 5.3+,在PHP

$query_date = '2010-02-04'; 
$date = new DateTime($query_date); 
//First day of month 
$date->modify('first day of this month'); 
$firstday= $date->format('Y-m-d'); 
//Last day of month 
$date->modify('last day of this month'); 
$lastday= $date->format('Y-m-d'); 

爲了找到下個月最後日期,修改如下,

$date->modify('last day of 1 month'); 
echo $date->format('Y-m-d'); 

等..

1
// First date of the current date 
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y'))); 
echo '<br />'; 
// Last date of the current date 
echo date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, date('Y'))); 
1
$month = 10; // october 

$firstday = date('01-' . $month . '-Y'); 
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y'); 
相關問題