phpのdatetime関数メモ

本ページにはプロモーションが含まれています。

phpで日付を扱う時によく使う「datetime」関数。
都度ググって探すのが面倒になってきたので、よく使うやつのメモです。

現在の時間を取得する(日本時間)

$get_date_now_obj = new Datetime('Asia/Tokyo');

指定の日時のdatetimeオブジェクト(日本時間)

$date_str = '2021-07-12 16:03:15';
$get_date_obj = new \DateTime($date_str, new \DateTimeZone('Asia/Tokyo'));

(4桁)年(2桁)月(2桁)日(2桁)時(2桁)分(2桁)秒のformat

$get_date_now_str = $get_date_now_obj->format('Y-m-d H:i:s');

0パディング無しの月日時format

$get_date_now_str = $get_date_now_obj->format('n-j G');

年、月、日、週、時、分、秒の加減をする

$get_date_obj->modify('+1 year');
$get_date_obj->modify('-2 month');
$get_date_obj->modify('+3 day');
$get_date_obj->modify('-4 week');
$get_date_obj->modify('+5 hour');
$get_date_obj->modify('-6 minute');
$get_date_obj->modify('+7 second');

時分秒を0にする

$get_date_obj->setTime( 0, 0, 0 );

本日か、未来か、過去かの判別

$diff_obj = $get_date_now_obj ->diff( $get_date_obj );
$diff_result = (int)$diff_obj->format( '%R%a' );
if(0 === $diff_result){
    print "本日\n";
}elseif( 1 <= $diff_result ){
    print "未来\n";
}elseif( -1 >= $diff_result ){
    print "過去\n";
}

unixtimeからオブジェクト生成

unixtimedayo=1681195752;
$date_obj = new DateTime('@' . $unixtimedayo);
$date_obj->setTimezone(new DateTimeZone('Asia/Tokyo'));

2つの日付(datatimeオブジェクト)の差を計算(秒)

$sabun_str = $mirai_date_obj->getTimestamp()-$now_date_obj->getTimestamp();
var_dump($sabun_str);
int(150);//150秒
php
Sabohをフォローする
左坊のメモ帳

コメント

タイトルとURLをコピーしました