简体   繁体   中英

How can I subtract a length of time from a datetime in PHP?

Suppose that I have datetime like 2013-01-16-0900 . How can I subtract a length of time - say, 30 minutes?

Is it stored as a string exactly like you posted, or is it actually a unix timestamp? If it's a string you can run strtotime on it then subtract 1800 (seconds) from it, and then convert it back with date() . That would probably be the easiest way.

This will subtract 30 minutes from the supplied timestamp.

echo date( 'Y-m-d-Hi', strtotime( $timestamp ) - 30 * 60 );

$timestamp = '2013-01-16-0900' in this example.

I have a strong preference towards using PHP's built in DateTime Module and adding or subtracting time using PHP's built in DateInterval Module . This allows you to perform reasonably complex date/time math and still respect the rules of time.

Also of note is DateTimeZone

Example Time

$dt = new DateTime("2013-01-16-0900", new DateTimeZone("America/Los_Angeles"));
$dt->setTimeZone("America/New_York");
$dt->sub(new DateInterval("PT30M"));
print $dt->format('Y-m-d H:i:s');

There is a bit of a learning curve to assembling time interval strings but once you figure it out, you should be able to write a re-usable function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM