略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: DateTimeZone::getOffset

2024-11-13

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getOffset -- timezone_offset_get返回相对于 GMT 的时差。

说明

面向对象风格

public DateTimeZone::getOffset(DateTime $datetime): int

过程化风格

timezone_offset_get(DateTimeZone $object, DateTime $datetime): int

该函数返回 datetime日期 相对于 GMT 的时差。 GMT 时差是通过 DateTimeZone 对象的时区信息计算出来的。

参数

object

仅过程化风格:由 timezone_open() 返回的 DateTimeZone 对象。

datetime

用来计算时差的日期对象。

返回值

成功时返回精确到秒的时差, 或者在失败时返回 false

范例

示例 #1 DateTimeZone::getOffset() 例子

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now"$dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now"$dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>
add a noteadd a note

User Contributed Notes 2 notes

up
1
DMJ
1 month ago
I came here looking for a way to get the offset between PHP's current default timezone and UTC. I went down the rabbit hole with DateTimeZone::getOffset, but it turns out there's a much easier way:

<?php
$offset
= date('O');
// Returns a string like '-0400'

$offset = date('P');
// Returns a string like '-04:00'

$offset = date('Z');
// Returns the offset in seconds, e.g. '-14400'
?>

To be clear, this gets whatever the timezone offset is *right now*, but I imagine that's what is wanted most of the time.

You can switch PHP's current timezone with date_default_timezone_set().
up
-1
Fred Gandt
7 years ago
Procedural Style:

<?php
// Don't know where the server is or how its clock is set, so default to UTC
date_default_timezone_set( "UTC" );

// The client is in England where daylight savings may be in effect
$daylight_savings_offset_in_seconds = timezone_offset_get( timezone_open( "BST" ), new DateTime() );

// Do something useful with the number
echo date( "U" ) + $daylight_savings_offset_in_seconds;
?>

官方地址:https://www.php.net/manual/en/datetimezone.getoffset.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3