How to Subtract 24 Hour from Date Time Object in PHP

Subtract 2 hours from time in php

You can use DateTime class for this.

 $DateTime = new DateTime();
$DateTime->modify('-2 hours');
echo $DateTime->format("Y-m-dTH:i:s");

How to subtract minutes from 24-hour time (HHMM)?

You can create DateTime object like that:

$open = date_create_from_format('Hi', '1000');
$close = date_create_from_format('Hi', '1900');

Then you can use DateTimeInterval

$interval15 = new \DateInterval('P0Y0DT0H15M');
$interval45 = new \DateInterval('P0Y0DT0H45M');

Then you can sub it from closing time and from open:

$now = new DateTime();
if ($now >= $open->sub($interval15) && $now <= $close->sub($interval45)) {
// logic
}

How to subtract 1 day 16 hours from datetime in PHP

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.

PHP DateTime operations - set new timezone and deduct 24 hours

As a sort of best practice, you can use this:

$serverDateTime = new DateTime();

$userTimezone = new DateTimeZone('Europe/London');

$userDateTime = $serverDateTime->setTimezone($userTimezone);

$dateInterval = new DateInterval('P1D');

echo $userDateTime->sub($dateInterval)->format('Y-m-d H:i:s');

But if you want to subtract directly from the variable, you can use this one:

$serverDateTime = new DateTime();

$userTimezone = new DateTimeZone('Europe/London');

$userDateTime = $serverDateTime->setTimezone($userTimezone)->sub(new DateInterval('P1D'))->format('Y-m-d H:i:s');

echo $userDateTime;

Subtract 1 day with PHP

You can try:

print('Next Date ' . date('Y-m-d', strtotime('-1 day', strtotime($date_raw))));

How to Subtract Minutes

Change the date into a timestamp (in seconds) then minus 15 minutes (in seconds) and then convert back to a date:

$date = date("Y-m-d H:i:s");
$time = strtotime($date);
$time = $time - (15 * 60);
$date = date("Y-m-d H:i:s", $time);


Related Topics



Leave a reply



Submit