Php - one hour earlier than date

I have a problem.

Suppose I have this type of time.

$date = strtotime($date); 

I need this to be converted to the Unix-timestamp format, but an hour earlier. I tried

 $date = strtotime($date-86400)
$date = strtotime($date-86400) 

but it seemed to me that this was wrong. He returned 0 when I sneaked into the table.

How can this be achieved?

Thanks.

+6
source share
5 answers

strtotime will give you the unix timestamp of your date. From this timestamp, you then subtract your hour:

 $date = strtotime($date) - 3600; // 3600 = 60 * 60 

If you call strtotime($date - 3600) , he likes to get the time for -3600 (e.g. strtotime(-3600) ), which does not make sense because strtotime expects a string as the first argument.

+4
source

You can do:

 $testDateStr = strtotime($date); $finalDate = date("Ymd H:i:s", strtotime("-1 hour", $testDateStr));
$testDateStr = strtotime($date); $finalDate = date("Ymd H:i:s", strtotime("-1 hour", $testDateStr)); 

Hope this helps

+5
source

86400 seconds - one day, not one hour.

The output of strtotime () is a unix timestamp. 3600 seconds earlier is a timestamp minus one hour. So:

 $date = strtotime($somestring); $hourago = $date - 3600; 

Or, depending on the original format of $ somestring:

 $hourago = strtotime($somestring . " - 1 hour"); 

And don't forget about date_default_timezone_set ()

+3
source

Try this request

 $query= "insert into yourTable(otherValues, date) values (otherFields, DATE_ADD(NOW(),INTERVAL -1 hour)) 

Use DATE_ADD to insert a date value that is 1 hour less than the current time.

+1
source

No one has proposed a solution to a DateTime object, so I will. This is the most advanced method of processing date and time and does not require the calculation of minutes and seconds.

I always like to write some kind of time zone declaration to make things final. Daylight saving time is usually a concern for date manipulation, but probably in this case. Feel free to change the time zone for your case.

PHP links:

Code (including formatted time for comparison) Demo link :

 $now=new DateTime('NOW UTC'); $now_stamp=$now->getTimestamp(); $formatted_now=$now->format("Ymd 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("Ymd H:i:s"); echo "$hour_ago_stamp ($formatted_hour_ago)"; 

Conclusion:

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

Source: https://habr.com/ru/post/909423/


All Articles