I'm trying subtracting Day and Hour from given date time example:
$schedule_date_time = '2016-02-29 08:30 PM';
echo date( "Y-m-d h:i a", strtotime("-1 day 16 hours", strtotime($schedule_date_time)) );
It gives me following result: 2016-02-29 12:30 pm
Which is not correct...
But If I do this :
$schedule_date_time = '2016-02-29 08:30 PM';
echo date( "Y-m-d h:i a", strtotime("-1 day -16 hours", strtotime($schedule_date_time)) );
It gives me following result: 2016-02-28 04:30 am
which is correct but is not possible for me to identify and put minus sign in string just before the integer.
Use date_sub
/DateTime::sub
.
$date = date_create("2016-02-29 08:30 PM") ;
date_sub($date, date_interval_create_from_date_string('1 day 16 hours'));
echo date_format($date, 'Y-m-d h:i a'); // 2016-02-28 04:30 am
If you want add an amount of time instead of subtracts it, use date_add
instead.
You can use DateTime::sub
class method along with DateInterval
class like as
$date2 = new DateTime('2016-02-29 08:30 PM');
$date2->sub(new DateInterval('P1DT16H'));
echo $date2->format("Y-m-d H:i:s");
The DateTime object is so powerful in PHP:
$dateTimeObj = DateTime::createFromFormat('Y-m-d H:i:s', '2016-04-04 15:20:00');
$dateTimeObj->modify('-1 day');
$dateTimeObj->modify('-16 hours');
echo $dateTimeObj->format('Y-m-d H:i:s');
It's very simple to use and very maintainable for future code-reviewers.