1

I have a question on taking timezones from users in PHP. I am getting user data on my server. In that user data, I am getting user date and time in UTC which is a default timezone.

For example- If the user sends data around 11:43 am, then in my end it's converting into UTC and getting time like 6:13 am (UTC+5:30). If the user sends data around 9:13 am, then it's coming at 6:13 am(UTC+3:00). I want user time at their end i.e., their timezone. The conclusion is need to get local time when we doesn't know timezone of user I tried many ways like DateTimeZone and date_default_timezone_set() and date_default_timezone_get(). Please help me out with this problem. Thanks in advance

Tejaswini
  • 31
  • 3
  • You'll have to send their local time along with the data. – Ro Achterberg Dec 01 '20 at 07:03
  • send this in the server https://stackoverflow.com/a/34602679/3859027 – Kevin Dec 01 '20 at 07:10
  • 1
    PHP has no way to determine reliably the browser's time zone because that isn't part of the HTTP protocol. You need to either figure out through an IP address database or write some client-side JavaScript code that submits the information. – Álvaro González Dec 01 '20 at 08:12

1 Answers1

1
  1. JavaScript time zone should be sent to the server via AJAX, it can be acquired using the following:

    if (typeof Intl == 'object' && typeof new Intl.DateTimeFormat().resolvedOptions == 'function' && typeof new Intl.DateTimeFormat().resolvedOptions().timeZone == 'string')

    {

    t = new Intl.DateTimeFormat().resolvedOptions().timeZone;

    }

  2. All SQL queries should use relative time zones for HTTP GET requests (e.g. SET time_zone = '-05:00') and UTC/GMT for HTTP POST requests (SET time_zone = '+00:00').

  3. Do not change the time zones any where else until you are ready to output a string to the client. Use the following:

Date Function:

function date_output($date, $format, $strtotime = '', $tz = true)
{
 date_default_timezone_set('UTC');

 if (ctype_digit($date)) {$dt = new DateTime(date('Y-m-d H:i:s', $date));}
 else {$dt = new DateTime($date);}

 if ($tz)
 {
  try
  {
   if (isset($_SESSION['time_zone']) && strlen($_SESSION['time_zone']) > 0) {$dt->setTimezone(new DateTimeZone($_SESSION['time_zone']));}
   else if (isset($_SESSION['time_zone_offset'])) {$tz = new DateTimeZone(($_SESSION['time_zone_offset'] * 36));}
  }
  catch (exception $e) {}//etc
 }

 if (strlen($strtotime) > 0) {$dt->modify($strtotime);}

 return $dt->format($format);
}

Using the function:

echo user_date_class($row1['date'], 'l F jS, Y, h:iA');
John
  • 1
  • 13
  • 98
  • 177