A common problem is to format dates and times for XML documents.
The XML standard is defined as follows:
"
To specify a time zone, you can either enter a dateTime in UTC time by adding a "Z" behind the time - like this:
<startdate>2002-05-30T09:30:10Z</startdate>
or you can specify an offset from the UTC time by adding a positive or negative time behind the time - like this:
<startdate>2002-05-30T09:30:10-06:00</startdate>
"
Here is a possible solution in PHP:
<?php
if(date_default_timezone_get() == 'UTC') {
$offsetString = 'Z'; // No need to calculate offset, as default timezone is already UTC
} else {
$phpTime = '2002-05-30 09:30:10';
$millis = strtotime($phpTime); // Convert time to milliseconds since 1970, using default timezone
$timezone = new DateTimeZone(date_default_timezone_get()); // Get default system timezone to create a new DateTimeZone object
$offset = $timezone->getOffset(new DateTime($phpTime)); // Offset in seconds to UTC
$offsetHours = round(abs($offset)/3600);
$offsetMinutes = round((abs($offset) - $offsetHours * 3600) / 60);
$offsetString = ($offset < 0 ? '-' : '+')
. ($offsetHours < 10 ? '0' : '') . $offsetHours
. ':'
. ($offsetMinutes < 10 ? '0' : '') . $offsetMinutes;
}
echo('<startdate>' . date('Y-m-d\TH:i:s', $millis) . $offsetString . '</startdate>'); // This is the correct XML format
?>
DateTimeZone::getOffset
timezone_offset_get
(PHP 5 >= 5.2.0)
DateTimeZone::getOffset -- timezone_offset_get — GMT からのタイムゾーンのオフセットを返す
説明
オブジェクト指向型
手続き型
この関数は、datetime パラメータで指定した 日付/時刻
についての GMT へのオフセットを返します。GMT オフセットの計算の際には、
使用する DateTimeZone オブジェクトに含まれるタイムゾーン情報を使用します。
パラメータ
-
object -
手続き型のみ: timezone_open() が返す DateTimeZone オブジェクト
-
datetime -
オフセットを計算する 日付/時刻 を含む DateTime。
返り値
成功した場合にタイムゾーンのオフセット秒数、失敗した場合に FALSE を返します。
例
例1 DateTimeZone::getOffset() の例
<?php
// ふたつのタイムゾーンオブジェクトを作成します。ひとつは台北 (台湾)、
// そしてもうひとつは東京 (日本) のものです。
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// 同一の Unix タイムスタンプを持つふたつの DateTime オブジェクトを作成します。
// しかしアタッチするタイムゾーンはそれぞれ異なります。
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);
// $dateTimeTaipei オブジェクトに含まれる 日付/時刻 の GMT オフセットを計算します。
// しかし、タイムゾーンの規則は東京のもの ($dateTimeZoneJapan)
// を使用します。
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// これは int(32400) となります (Sat Sep 8 01:00:00 1951 JST 以降の日付の場合)。
var_dump($timeOffset);
?>
skanzow at gmx dot net ¶
1 year ago
