2

私はこれについて数時間頭を悩ませてきましたが、助けを求めることにしました。

ユーザーが日付と時刻を選択できるように、JavaScriptカレンダーを使用しています。今度は、この時間を THEIR タイムゾーン (既にデータベースに記録しています) に相対的にしたいと考えています。ただし、入力を保存する方法に頭を悩ませることはできません。mktime がユーザーのタイムゾーンに出力する UTC タイムスタンプを調整する必要があることはわかっていますが、問題が発生しています。

これは私が試したことです:

$time = $_POST['datetime']; // Dont worry I will sanitize the input
echo $time.'<br>';
$timezone = "Canada/Pacific"; // Just an example, this will be taken from the database
$timestamp = mktime($hours, $minute, 0, $month, $day, $year); // Based on $time, I just ignored my steps to get the hours etc here
date_default_timezone_set($timezone);
echo 'Your timezone: '.date("F j Y h:i:s A", $timestamp).'<br />';
date_default_timezone_set('UTC');
echo 'UTC: '.date("F j Y h:i:s A", $timestamp);

上記を実行すると、次のような出力が得られます。

30 October 2013 - 01:00 AM
Your timezone: October 29 2013 11:00:00 PM
UTC: October, 30 2013 06:00:00 AM

問題は、ユーザーが午前 1:00 を入力しても、mktime がそれを 1:00 の UTC タイムスタンプに変換することを期待していましたが、実際には午前 6:00 の UTC タイムスタンプに変換されているようです。5 時間の差がどこから来ているのかわかりません。そこに静的な 5 時間の差をコーディングしたくありません。

それが修正された後、タイムスタンプをUTCタイムスタンプとして保存したいと思います。これは、将来タイムスタンプを取得して実行する場合に備えて調整されています。

$timezone = "Canada/Pacific";
date_default_timezone_set($timezone);
echo 'Time: '.date("F j Y h:i:s A", $timestamp); // $timestamp from the database

出力する必要があること:

30 October 2013 - 01:00 AM

どんな助けでも大歓迎です!

4

1 に答える 1

2

Use DateTime and DateTimezone, and your life will be easier.

If posted datetime is in UTC, you can simple create DateTime object in UTC timezone like this:

$dt = new DateTime($_POST['datetime'], new DateTimezone('UTC'));
echo $dt->format('F j Y h:i:s A P');

If you wish to change timezone to users, you can call setTimezone() on DateTime object:

$dt->setTimezone(new DateTimezone('Canada/Pacific'));
echo $dt->format('F j Y h:i:s A P');

Try demo.


If your posted datetime is like 30 October 2013 - 01:00 AM, then you cannot use new DateTime() or strtotime() because it is not standard datetime format. In that case, you can use DateTime::createFromFormat like this:

$dt = DateTime::createFromFormat('j F Y - h:i A', $_POST['datetime'], new DateTimezone('UTC'));

Try demo.

于 2013-11-13T14:29:58.877 に答える