Get the timestamp of exactly one week ago in PHP?

前端 未结 6 1144
一整个雨季
一整个雨季 2021-02-05 00:55

I need to calculate the timestamp of exactly 7 days ago using PHP, so if it\'s currently March 25th at 7:30pm, it would return the timestamp for March 18th at 7:30pm.

Sh

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 01:01

    From PHP 5.2 you can use DateTime:

    $timestring="2015-03-25";
    $datetime=new DateTime($timestring);
    $datetime->modify('-7 day');
    echo $datetime->format("Y-m-d"); //2015-03-18
    

    Instead of creating DateTime with string, you can setTimestamp directly on object:

    $timestamp=1427241600;//2015-03-25
    $datetime=new DateTime();
    $datetime->setTimestamp($timestamp);
    $datetime->modify('-7 day');
    echo $datetime->format("Y-m-d"); //2015-03-18
    

提交回复
热议问题