計算のために、特定の月の終了日を取得する必要があります。
PHPでそれを行うにはどうすればよいですか?date()関数を使用してみましたが、機能しませんでした。
私はこれを使用しました:
date($year.'-'.$month.'-t');
しかし、これは今月の終了日を示します。私はどこかが間違っていると思います。ここでどこが間違っているのかわかりませんでした。
年を2012、月を03とすると、2012-03-31と表示されます。
このコードは、特定の月の最終日を示します。
$datetocheck = "2012-03-01";
$lastday = date('t',strtotime($datetocheck));
date()
呼び出しを次のように置き換えます。
date('Y-m-t', strtotime($year.'-'.$month.'-01'));
の最初のパラメーターdate()
は返される形式であり、2 番目のパラメーターは UNIX タイムスタンプでなければなりません (または現在のタイムスタンプを使用するために渡されません)。あなたの場合、関数strtotime()
でタイムスタンプを生成し、年、月、および日の 01 を含む日付文字列を渡します。同じ年と月が返され-t
ますが、形式は月の最終日に置き換えられます。
年月なしで月の最終日のみを返したい場合:
date('t', strtotime($year.'-'.$month.'-01'));
't'
フォーマット文字列として使用してください。
今月:
echo date('Y-m-t');
任意の月:
echo date('Y-m-t', strtotime("$year-$month-1"));
以下のコードを試してください。
$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));
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);
}
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();
これを試してみてください。これにより、現在の月の開始日と終了日が得られます。
date("Y-m-d",strtotime("-1 day" ,strtotime("+1 month",strtotime(date("m")."-01-".date("Y")))));
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]}";
}