php - One Hour Earlier Than Given Datetime

前端 未结 5 557
不思量自难忘°
不思量自难忘° 2020-12-20 14:16

I\'m having a problem here..

Supposed I have this kind of datetime.


$date = strtotime($date);

I need this to be converted into t

5条回答
  •  情深已故
    2020-12-20 14:45

    Nobody offered a DateTime object solution yet, so I will. It is the most modern method for handling datetime and doesn't require any calculation of minutes & seconds.

    I always like to drop in some sort of timezone declaration to make things definitive. Daylight Saving Time is normally a concern with datetime manipulations, but probably okay in this case. Feel free to modify the timezone for your case.

    PHP manual links:

    • DateTime Object
    • DateTime modify()
    • DateTime getTimestamp()
    • DateTime format()
    • Timezone List

    Code (including formatted time for comparison) Demo Link:

    $now=new DateTime('NOW UTC');
    
    $now_stamp=$now->getTimestamp();
    $formatted_now=$now->format("Y-m-d H:i:s");
    echo "$now_stamp ($formatted_now)\n";
    
    $hour_ago=$now->modify('-1 hour');
    $hour_ago_stamp=$hour_ago->getTimestamp();
    $formatted_hour_ago=$hour_ago->format("Y-m-d H:i:s");
    echo "$hour_ago_stamp ($formatted_hour_ago)";
    

    Output:

    1492687193 (2017-04-20 11:19:53)
    1492683593 (2017-04-20 10:19:53)
    

提交回复
热议问题