Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract 1 day 16 hours from datetime in PHP

Tags:

php

strtotime

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.

like image 479
AngularLearner Avatar asked Dec 28 '25 13:12

AngularLearner


1 Answers

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.

like image 75
Federkun Avatar answered Dec 31 '25 03:12

Federkun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!