函数名:DateTimeZone::getOffset()
适用版本:PHP 5 >= 5.2.0, PHP 7
用法:DateTimeZone::getOffset() 函数返回与 GMT(格林尼治标准时间)的偏移秒数。可以使用 DateTimeZone 对象的实例调用此函数。
语法:int DateTimeZone::getOffset(DateTimeInterface $datetime)
参数:
- DateTimeInterface $datetime:一个实现了 DateTimeInterface 接口的日期时间对象。可以是 DateTime 或 DateTimeImmutable 类的实例。
返回值: 返回一个整数,表示与 GMT 的偏移秒数。正数表示比 GMT 更早,负数表示比 GMT 更晚。
示例:
// 创建一个日期时间对象
$datetime = new DateTime('now', new DateTimeZone('Asia/Shanghai'));
// 获取时区偏移秒数
$offset = $datetime->getTimezone()->getOffset($datetime);
// 格式化为友好的时区格式(e.g., +07:00)
$offset_formatted = sprintf('%s%02d:%02d', ($offset >= 0 ? '+' : '-'), abs($offset / 3600), abs($offset % 3600) / 60);
echo "当前时区偏移:{$offset} 秒<br>";
echo "友好的时区格式:{$offset_formatted}<br>";
输出:
当前时区偏移:28800 秒
友好的时区格式:+08:00
上述示例中,我们创建了一个当前日期时间的对象,并将时区设置为 'Asia/Shanghai'。然后,我们使用 getOffset()
函数获取当前时区的偏移秒数,并将其格式化为友好的时区格式,例如 '+08:00'。最后,我们输出偏移秒数和友好的格式。