0

I need a user to be able to select a timezone for, lets say, some "broadcast". I need to save only the timezone_offset value of the selected timezone BUT in seconds. Like:

+03:00 should be save to the database like 10800 , or if -03:00 this should be save like -10800

so + offtests should be saved as just the number in seconds without the plus sign and - offsets should be saved with the minus sign -10800

I found this function:

<?php
/**
 * Timezones list with GMT offset
 *
 * @return array
 * @link http://stackoverflow.com/a/9328760
 */
function tz_list() {
  $zones_array = array();
  $timestamp = time();
  foreach(timezone_identifiers_list() as $key => $zone) {
    date_default_timezone_set($zone);
    $zones_array[$key]['zone'] = $zone;
    $zones_array[$key]['diff_from_GMT'] = 'UTC/GMT ' . date('P', $timestamp);
  }
  return $zones_array;
}
?>

So this:

<div style="margin-top: 20px;">
  <select style="font-family: 'Courier New', Courier, monospace; width: 450px;">
    <option value="0">Please, select timezone</option>
    <?php foreach(tz_list() as $t) { ?>
      <option value="<?php print $t['zone'] ?>">
        <?php print $t['diff_from_GMT'] . ' - ' . $t['zone'] ?>
      </option>
    <?php } ?>
  </select>
</div>

gives me this:

                <option value="Africa/Abidjan">
                UTC/GMT +00:00 - Africa/Abidjan </option>
                    <option value="Africa/Accra">
                UTC/GMT +00:00 - Africa/Accra </option>
                    <option value="Africa/Addis_Ababa">
                UTC/GMT +03:00 - Africa/Addis_Ababa </option>
                    <option value="Africa/Algiers">
                UTC/GMT +01:00 - Africa/Algiers </option>

But I would need the values to be 10800 or -10800 depending on the selected timzone.

My environment is laravel 5.1* so I also have carbon available maybe that could help.

So the essential question is, how to convert timezone offset format "+03:00" to "10800" and "-03:00" to "-10800"

Gabriel Stein
  • 428
  • 1
  • 4
  • 22

1 Answers1

3

You can get the time zone's offset by utilizing PHP's native DateTimeZone object. Here's updated tz_list():

function tz_list() {
  $zones_array = array();
  $timestamp = time();
  $dummy_datetime_object = new DateTime();
  foreach(timezone_identifiers_list() as $key => $zone) {
    date_default_timezone_set($zone);
    $zones_array[$key]['zone'] = $zone;
    $zones_array[$key]['diff_from_GMT'] = 'UTC/GMT ' . date('P', $timestamp);

    $tz = new DateTimeZone($zone);
    $zones_array[$key]['offset'] = $tz->getOffset($dummy_datetime_object);
  }

  return $zones_array;
}

Use offset as value for your select's options.

Oliver Maksimovic
  • 3,204
  • 3
  • 28
  • 44