以下是一個實現將指定時間與時間戳進行加減後,輸出指定格式時間的PHP函數:
<?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'
?>可以將以上代碼保存爲一個PHP文件,並在需要的地方調用該函數來實現指定時間與時間戳的加減。在調用該函數時,您需要傳遞三個參數:
$time:日期時間字符串,格式爲 'Y-m-d H:i:s'$seconds:要添加或減去的秒數,正數爲加,負數爲減$format:輸出的日期時間格式,默認爲 'Y-m-d H:i:s',您可以根據需要自行指定。
函數將返回格式化後的日期時間字符串