2012-05-28 40 views
0

我需要一些計算目的的給定月份的結束日期的結束日期,獲取給定月份

我怎麼能做到這一點在PHP中,我嘗試使用日期()函數,但它沒沒有工作。

我用這個:

date($year.'-'.$month.'-t'); 

但是這給當月的結束日期。 我覺得我錯了某個地方,我找不到我要去的地方。

如果我將2012年的&月份作爲03,那麼它必須顯示爲2012-03-31。

回答

4

此代碼會給你最後一天的特定月份。

$datetocheck = "2012-03-01"; 
$lastday = date('t',strtotime($datetocheck)); 
+0

作品完美:) 感謝很多:) –

+0

雅,我是想,但問題是我有一個顯示說,要等7分鐘;) –

0

請嘗試以下代碼。

$m = '03';// 
$y = '2012'; // 

$first_date = date('Y-m-d',mktime(0, 0, 0, $m , 1, $y)); 

$last_day = date('t',strtotime($first_date)); 
$last_date = date('Y-m-d',mktime(0, 0, 0, $m ,$last_day, $y)); 
0
function lastday($month = '', $year = '') { 
    if (empty($month)) { 
     $month = date('m'); 
    } 
    if (empty($year)) { 
     $year = date('Y'); 
    } 
    $result = strtotime("{$year}-{$month}-01"); 
    $result = strtotime('-1 second', strtotime('+1 month', $result)); 
    return date('Y-m-d', $result); 
} 
0
function firstOfMonth() { 
return date("Y-m-d", strtotime(date('m').'/01/'.date('Y').' 00:00:00')). 'T00:00:00';} 

function lastOfMonth() { 
return date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')))). 'T23:59:59';} 

$date1 = firstOfMonth(); 
$date2 = lastOfMonth(); 

試試這個,這會給你一個當月的開始和結束日期。

0
date("Y-m-d",strtotime("-1 day" ,strtotime("+1 month",strtotime(date("m")."-01-".date("Y"))))); 
1

本月:

echo date('Y-m-t'); 

任何一個月:

echo date('Y-m-t', strtotime("$year-$month-1")); 
2

要替換你的date()來電與:

date('Y-m-t', strtotime($year.'-'.$month.'-01')); 

date()的第一個參數是格式你想要返回,第二個參數必須是一個unix時間戳(或不傳遞使用當前時間戳)。在你的情況下,你可以使用函數strtotime()生成一個時間戳,並將日期字符串與年份,月份和01一起傳遞給一天。它將返回同一年份和月份,但格式中的-t將被本月的最後一天取代。

如果你只想返回該月的最後一天,沒有年份和月份:

date('t', strtotime($year.'-'.$month.'-01')); 

只需使用't'作爲格式字符串。

0
function getEndDate($year, $month) 
{ 
    $day = array(1=>31,2=>28,3=>31,4=>30,5=>31,6=>30,7=>31,8=>31,9=>30,10=>31,11=>30,12=>31); 
    if($year%100 == 0) 
    { 
     if($year%400 == 0) 
     $day[$month] = 29; 
    } 
    else if($year%4 == 0) 
     $day[$month] = 29; 

    return "{$year}-{$month}-{$day[$month]}"; 
} 
0

如果您使用PHP> = 5.2,我強烈建議您使用新的DateTime對象。例如象下面這樣:

$a_date = "2012-03-23"; 
$date = new DateTime($a_date); 
$date->modify('last day of this month'); 
echo $date->format('Y-m-d');