2016-12-10 8 views
1

にタイムスタンプする日付値(文字列)に変換私はこのような日付の値があります。異なるタイムゾーン

$date_value = "2016-12-10 11:28:36"; 

を私のタイムゾーン3:30は、GMTからのオフセット(それがGTM3なったAsia/Tehran、あります:30+)。私はコンテンツを14:58に保存しましたが、上記の値($date_value)で項目を保存しました。これはGMT(GMT00)からのオフセットがないサーバーのタイムゾーンを使用しているため論理的です。

"アジア/テヘラン"という希望のタイムゾーンに日付を戻したいのですが、私の日付手順は期待どおりには機能しません(「予想通り私は日付時刻を14に戻さない:テヘランのベースの時間である00)ここで私が使用したコードです::59。。

$DateTime = new DateTime($date_value, new DateTimeZone("Asia/Tehran")); 

print $DateTime->format($format); // edited the question with on this line 

しかし、変更がないかのように、正確な日付をバックプリントは

それは常に動作しますが、この特定のケースではなぜうまくいかないのか分かりません。私はここで何か間違っていますか?

+0

どのように動作しませんか? –

+0

質問を編集しました。 –

+0

はい、私の間違いです。私はformat()を意味します –

答えて

2

サーバーから取得する日付文字列がUTCの場合は、DateTimeオブジェクトをUTCで作成し、タイムゾーンを変更する必要があります。

$format = "Y-m-d H:i:s"; 
$date_value = "2016-12-10 11:28:36"; 

$DateTime = new DateTime($date_value, new DateTimeZone("UTC")); 
$DateTime->setTimezone(new DateTimeZone("Asia/Tehran")); 
print $DateTime->format($format); 

// Outputs: 2016-12-10 14:58:36 
+0

キーは「UTC」でした。どうもありがとう –

1

文字列からDateTimeオブジェクトを作成します。

$date_value = "2016-12-10 11:28:36"; 
$date = new DateTime($date_value); 

設定のタイムゾーン:

$date->setTimezone(new DateTimeZone("Asia/Tehran")); 

を取得し、フォーマット日:

echo $date->format('Y-m-d H:i:s (e) P') . "\n"; 

このコードは、ときにそれがどのように動作するかを示しDateTime objのタイムゾーンを変更する電気ショック療法:

<?php 
$date_value = "2016-12-10 11:28:36"; 

$date = new DateTime($date_value); 
$date->setTimezone(new DateTimeZone("Asia/Tehran")); 
echo $date->format('Y-m-d H:i:s (e) P') . "\n"; 

$date->setTimezone(new DateTimeZone('Europe/Warsaw')); 
echo $date->format('Y-m-d H:i:s (e) P') . "\n"; 

出力:http://php.net/manual/en/datetime.settimezone.php

を(あなたのコードが動作しないのDateTimeコンストラクタメソッドでタイムゾーンパラメータは、この指定された時間帯に日付を作成するために:あなたはここで読むことができます

2016-12-10 22:58:36 (Asia/Tehran) +03:30 
2016-12-10 20:28:36 (Europe/Warsaw) +01:00 

詳しい情報)

関連する問題