Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, use strtotime to subtract minutes from a date-time variable?

Tags:

php

strtotime

I need to subtract 45 minutes from the date-time variable in PHP.

The code:

$thestime = '2012-07-27 20:40';
$datetime_from = date("Y-m-d h:i",strtotime("-45 minutes",strtotime($thestime)));
echo $datetime_from;

returns the result 2012-07-27 07:55.

It should be 2012-07-27 19:55, though. How do I fix this?

like image 455
Klausos Klausos Avatar asked Jul 27 '12 13:07

Klausos Klausos


People also ask

What is the use of Strtotime in PHP?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.

How do I convert Strtotime to date format?

Code for converting a string to dateTime$date = strtotime ( $input ); echo date ( 'd/M/Y h:i:s' , $date );

Why is Strtotime return false?

strtotime expects a "English textual datetime" (according to the manual), which Y-D-M is not. Any time strtotime returns false, it simply doesn't understand your string, which in this application is expected.


1 Answers

You should do:

$datetime_from = date("Y-m-d H:i", strtotime("-45 minutes", strtotime($thestime)));

Having H instead of h means a 24-hour format is used, representing the hour with leading zeros: 00 through 23.

You can read more on this in the PHP date function documentation.


There are also object oriented ways of doing this which are more fluent, like DateTime::sub:

$datetime_from = (new DateTime($thestime))->sub(DateInterval::createFromDateString('45 minutes'))->format('Y-m-d H:i')

Or the even more expressive way offered by the Carbon library which extends PHP's built in DateTime class:

$datetime_from = (new Carbon($thestime))->subMinutes(45)->format('Y-m-d H:i');
like image 135
Bogdan Avatar answered Oct 02 '22 12:10

Bogdan