ここでは色々な日付を文字列で取得する方法を関数別に分けて記載してます
DateTimeを使用
-
今日を文字列(yyyy-mm-dd)で取得
$date = new DateTime('now'); echo $date->format('Y-m-d'); -
昨日を文字列(yyyy-mm-dd)で取得
$date = new DateTime('-1 day'); echo $date->format('Y-m-d'); -
今日の月末の文字列(yyyy-mm-dd)で取得
$date = new DateTime('now'); echo $date->format('Y-m-t');$date = new DateTime('last day of this month'); echo $date->format('Y-m-d'); -
yyyy-mm-ddの文字列から対象日の月初を取得
$target_date = '2023-05-10'; $date = new DateTime($target_date); echo $date->format('Y-m-01'); -
yyyy-mm-ddの文字列から対象日の月末を取得
$target_date = '2023-05-10'; $date = new DateTime($target_date); echo $date->format('Y-m-t');
strtotimeを使用
-
今日を文字列(yyyy-mm-dd)で取得
echo date('Y-m-d', strtotime('now')); -
昨日を文字列(yyyy-mm-dd)で取得
echo date('Y-m-d', strtotime('-1 day', time())); -
今日の月末の文字列(yyyy-mm-dd)で取得
echo date('Y-m-t', strtotime('now'));echo date('Y-m-d', strtotime('last day of now')); -
yyyy-mm-ddの文字列から対象日の前日を取得
$target_date = '2023-05-10'; echo date('Y-m-d', strtotime($target_date . '-1 day'));$target_date = '2023-05-10'; echo date('Y-m-d', strtotime('-1 day', strtotime($target_date))); -
yyyy-mm-ddの文字列から対象日の月初を取得
$target_date = '2023-05-10'; echo date('Y-m-01', strtotime($target_date));$target_date = '2023-05-10'; echo date('Y-m-d', strtotime('first day of ' . $target_date)); -
yyyy-mm-ddの文字列から対象日の月末を取得
$target_date = '2023-05-01'; echo date('Y-m-t', strtotime($target_date));$target_date = '2023-05-01'; echo date('Y-m-d', strtotime('last day of ' . $target_date));