Here is a PHP function that adds or subtracts a specified amount of time from a timestamp and then outputs the resulting time in a specified format:
<?php
/**
* 将指定时间与时间戳相加减后,输出指定格式时间
*
* @param string $time 日期时间字符串,格式为 'Y-m-d H:i:s'
* @param int $seconds 要添加或减去的秒数,正数为加,负数为减
* @param string $format 输出的日期时间格式,默认为 'Y-m-d H:i:s'
* @return string 格式化后的日期时间字符串
*/
function add_seconds_to_time($time, $seconds, $format = 'Y-m-d H:i:s') {
// 将日期时间字符串转换为时间戳
$timestamp = strtotime($time);
// 计算加减后的时间戳
$new_timestamp = $timestamp + $seconds;
// 将时间戳格式化为指定格式的日期时间字符串
$new_time = date($format, $new_timestamp);
// 返回格式化后的日期时间字符串
return $new_time;
}
// 示例用法
$time = '2023-04-25 13:03:02';
$seconds = 3600; // 假设要将时间加上1小时
$new_time = add_seconds_to_time($time, $seconds);
echo $new_time; // 输出 '2023-04-25 14:03:02'
?>You can save the above code as a PHP file and call this function wherever needed to add or subtract a specified amount of time from or to a timestamp. When calling this function, you must pass three parameters:
$timeDate and time string in the format 'Y-m-d H:i:s'$secondsThe number of seconds to add or subtract; a positive value adds seconds, while a negative value subtracts seconds.$formatThe output date and time format defaults to 'Y-m-d H:i:s'; you can specify a custom format as needed.
The function returns a formatted date and time string.