PHP计算相对时间差函数示例
在PHP开发中,有时需要获取相对于当前时间的特定时间段之前的日期。以下代码展示了如何编写简单的辅助函数来实现这一需求。
以下是具体的实现代码:
// 计算几周前或几周后的时间 function GetDiffWeek($Week, $type = 'l') { if (!strcmp($type, 'b')) $res = date("Y-m-d H:i:s", strtotime("-$Week week")); if (!strcmp($type, 'l')) $res = date("Y-m-d H:i:s", strtotime("+$Week week")); return $res; } // 计算几天前或几天后的时间 function GetDiffDays($days, $type = 'l') { if (!strcmp($type, 'b')) $res = date("Y-m-d H:i:s", strtotime("-$days day")); if (!strcmp($type, 'l')) $res = date("Y-m-d H:i:s", strtotime("+$days day")); return $res; } // 计算几年前或几年后的时间 function GetDiffYears($year, $type = 'l') { if (!strcmp($type, 'b')) $res = date("Y-m-d H:i:s", strtotime("-$year year")); if (!strcmp($type, 'l')) $res = date("Y-m-d H:i:s", strtotime("+$year year")); return $res; }