0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPでの日付取得処理

Last updated at Posted at 2023-05-27

ここでは色々な日付を文字列で取得する方法を関数別に分けて記載してます

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));
    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?