Timezone conversion in php












45















Can anyone suggest an easy method to convert date and time to different timezones in php?










share|improve this question





























    45















    Can anyone suggest an easy method to convert date and time to different timezones in php?










    share|improve this question



























      45












      45








      45


      27






      Can anyone suggest an easy method to convert date and time to different timezones in php?










      share|improve this question
















      Can anyone suggest an easy method to convert date and time to different timezones in php?







      php datetime timezone timestamp






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 21 '14 at 5:38









      BlitZ

      10.5k33756




      10.5k33756










      asked Mar 24 '10 at 6:08









      rakiraki

      1,06872639




      1,06872639
























          8 Answers
          8






          active

          oldest

          votes


















          99














          You can use the datetime object or their function aliases for this:



          Example (abridged from PHP Manual)



          date_default_timezone_set('Europe/London');

          $datetime = new DateTime('2008-08-03 12:35:23');
          echo $datetime->format('Y-m-d H:i:s') . "n";
          $la_time = new DateTimeZone('America/Los_Angeles');
          $datetime->setTimezone($la_time);
          echo $datetime->format('Y-m-d H:i:s');




          Edit regarding comments




          but i cannt use this method because i need to show date in different time zones as the user login from different locations




          That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.




          in the database i need to get the dates in any single timezone, then only it can be processed properly




          You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.






          share|improve this answer


























          • thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

            – raki
            Mar 24 '10 at 6:25













          • @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

            – zerkms
            Mar 24 '10 at 6:44













          • that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

            – raki
            Mar 24 '10 at 6:51






          • 8





            In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

            – Jacco
            Mar 24 '10 at 10:08






          • 1





            all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

            – Kinjal Dixit
            Nov 24 '12 at 6:22



















          14














          An even simpler method looks like this:



          date_default_timezone_set('Europe/London'); // your user's timezone
          $my_datetime='2013-10-23 15:47:10';
          echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));


          As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.



          I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.






          share|improve this answer































            11














            This worked for me and it's pretty clean too!



            function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
            {
            try {
            $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
            $dateTime->setTimezone(new DateTimeZone($userTimeZone));
            return $dateTime->format($format);
            } catch (Exception $e) {
            return '';
            }
            }

            function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
            {
            try {
            $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
            $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
            return $dateTime->format($format);
            } catch (Exception $e) {
            return '';
            }
            }

            //example usage
            $serverDate = $userDate = '2014-09-04 22:37:22';
            echo convert_to_user_date($serverDate);
            echo convert_to_server_date($userDate);





            share|improve this answer

































              7














              None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.



              Here is my solution:



              function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
              {
              if (empty($timeZoneSource)) {
              $timeZoneSource = date_default_timezone_get();
              }
              if (empty($timeZoneTarget)) {
              $timeZoneTarget = date_default_timezone_get();
              }

              $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
              $dt->setTimezone(new DateTimeZone($timeZoneTarget));

              return $dt->format("Y-m-d H:i:s");
              }


              So, to convert to the server default, you would just pass one timezone:



              changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");


              To convert from the server default to the user, you would leave the 2nd parameter null or blank:



              changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");


              And to switch between to timezones unrelated to the default, you would provide 2 timezones:



              changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");





              share|improve this answer


























              • Seems to work great!

                – Adam F
                Jan 26 '17 at 21:44






              • 1





                Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                – Ajay Singh
                Jan 13 '18 at 19:13



















              5














              DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object



              Object oriented style



              <?php
              $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
              echo $date->format('Y-m-d H:i:sP') . "n";

              $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
              echo $date->format('Y-m-d H:i:sP') . "n";
              ?>


              Procedural style



              <?php
              $date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
              echo date_format($date, 'Y-m-d H:i:sP') . "n";

              date_timezone_set($date, timezone_open('Pacific/Chatham'));
              echo date_format($date, 'Y-m-d H:i:sP') . "n";
              ?>


              The above examples will output:



              2000-01-01 00:00:00+12:00
              2000-01-01 01:45:00+13:45





              share|improve this answer































                3














                UTC to local:



                <?php
                $datetime = date("Y-m-d H:i:s");
                $utc = new DateTime($datetime, new DateTimeZone('UTC'));
                $utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
                echo $utc->format('Y-m-d H:i:s');

                ?>





                share|improve this answer

































                  1














                  // Convert date from one zone to another..
                  /*
                  $zone_from='Asia/Kolkata';



                  $zone_to='America/Phoenix';

                  date_default_timezone_set($zone_from);

                  $convert_date="2016-02-26 10:35:00";

                  echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);

                  */
                  function zone_conversion_date($time, $cur_zone, $req_zone)
                  {
                  date_default_timezone_set("GMT");
                  $gmt = date("Y-m-d H:i:s");

                  date_default_timezone_set($cur_zone);
                  $local = date("Y-m-d H:i:s");

                  date_default_timezone_set($req_zone);
                  $required = date("Y-m-d H:i:s");

                  /* return $required; */
                  $diff1 = (strtotime($gmt) - strtotime($local));
                  $diff2 = (strtotime($required) - strtotime($gmt));

                  $date = new DateTime($time);
                  $date->modify("+$diff1 seconds");
                  $date->modify("+$diff2 seconds");

                  return $timestamp = $date->format("Y-m-d H:i:s");
                  }





                  share|improve this answer































                    0














                    <?php
                    $time='6:02';
                    $dt = new DateTime($time, new DateTimeZone('America/New_York'));
                    //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
                    $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                    echo $dt->format('H:i') . PHP_EOL;
                    ?>





                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function () {
                      StackExchange.using("externalEditor", function () {
                      StackExchange.using("snippets", function () {
                      StackExchange.snippets.init();
                      });
                      });
                      }, "code-snippets");

                      StackExchange.ready(function() {
                      var channelOptions = {
                      tags: "".split(" "),
                      id: "1"
                      };
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function() {
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled) {
                      StackExchange.using("snippets", function() {
                      createEditor();
                      });
                      }
                      else {
                      createEditor();
                      }
                      });

                      function createEditor() {
                      StackExchange.prepareEditor({
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader: {
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      },
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      });


                      }
                      });














                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2505681%2ftimezone-conversion-in-php%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      8 Answers
                      8






                      active

                      oldest

                      votes








                      8 Answers
                      8






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      99














                      You can use the datetime object or their function aliases for this:



                      Example (abridged from PHP Manual)



                      date_default_timezone_set('Europe/London');

                      $datetime = new DateTime('2008-08-03 12:35:23');
                      echo $datetime->format('Y-m-d H:i:s') . "n";
                      $la_time = new DateTimeZone('America/Los_Angeles');
                      $datetime->setTimezone($la_time);
                      echo $datetime->format('Y-m-d H:i:s');




                      Edit regarding comments




                      but i cannt use this method because i need to show date in different time zones as the user login from different locations




                      That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.




                      in the database i need to get the dates in any single timezone, then only it can be processed properly




                      You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.






                      share|improve this answer


























                      • thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                        – raki
                        Mar 24 '10 at 6:25













                      • @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                        – zerkms
                        Mar 24 '10 at 6:44













                      • that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                        – raki
                        Mar 24 '10 at 6:51






                      • 8





                        In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                        – Jacco
                        Mar 24 '10 at 10:08






                      • 1





                        all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                        – Kinjal Dixit
                        Nov 24 '12 at 6:22
















                      99














                      You can use the datetime object or their function aliases for this:



                      Example (abridged from PHP Manual)



                      date_default_timezone_set('Europe/London');

                      $datetime = new DateTime('2008-08-03 12:35:23');
                      echo $datetime->format('Y-m-d H:i:s') . "n";
                      $la_time = new DateTimeZone('America/Los_Angeles');
                      $datetime->setTimezone($la_time);
                      echo $datetime->format('Y-m-d H:i:s');




                      Edit regarding comments




                      but i cannt use this method because i need to show date in different time zones as the user login from different locations




                      That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.




                      in the database i need to get the dates in any single timezone, then only it can be processed properly




                      You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.






                      share|improve this answer


























                      • thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                        – raki
                        Mar 24 '10 at 6:25













                      • @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                        – zerkms
                        Mar 24 '10 at 6:44













                      • that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                        – raki
                        Mar 24 '10 at 6:51






                      • 8





                        In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                        – Jacco
                        Mar 24 '10 at 10:08






                      • 1





                        all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                        – Kinjal Dixit
                        Nov 24 '12 at 6:22














                      99












                      99








                      99







                      You can use the datetime object or their function aliases for this:



                      Example (abridged from PHP Manual)



                      date_default_timezone_set('Europe/London');

                      $datetime = new DateTime('2008-08-03 12:35:23');
                      echo $datetime->format('Y-m-d H:i:s') . "n";
                      $la_time = new DateTimeZone('America/Los_Angeles');
                      $datetime->setTimezone($la_time);
                      echo $datetime->format('Y-m-d H:i:s');




                      Edit regarding comments




                      but i cannt use this method because i need to show date in different time zones as the user login from different locations




                      That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.




                      in the database i need to get the dates in any single timezone, then only it can be processed properly




                      You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.






                      share|improve this answer















                      You can use the datetime object or their function aliases for this:



                      Example (abridged from PHP Manual)



                      date_default_timezone_set('Europe/London');

                      $datetime = new DateTime('2008-08-03 12:35:23');
                      echo $datetime->format('Y-m-d H:i:s') . "n";
                      $la_time = new DateTimeZone('America/Los_Angeles');
                      $datetime->setTimezone($la_time);
                      echo $datetime->format('Y-m-d H:i:s');




                      Edit regarding comments




                      but i cannt use this method because i need to show date in different time zones as the user login from different locations




                      That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.




                      in the database i need to get the dates in any single timezone, then only it can be processed properly




                      You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jul 21 '15 at 20:01









                      datagutten

                      13319




                      13319










                      answered Mar 24 '10 at 6:11









                      GordonGordon

                      263k58465506




                      263k58465506













                      • thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                        – raki
                        Mar 24 '10 at 6:25













                      • @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                        – zerkms
                        Mar 24 '10 at 6:44













                      • that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                        – raki
                        Mar 24 '10 at 6:51






                      • 8





                        In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                        – Jacco
                        Mar 24 '10 at 10:08






                      • 1





                        all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                        – Kinjal Dixit
                        Nov 24 '12 at 6:22



















                      • thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                        – raki
                        Mar 24 '10 at 6:25













                      • @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                        – zerkms
                        Mar 24 '10 at 6:44













                      • that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                        – raki
                        Mar 24 '10 at 6:51






                      • 8





                        In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                        – Jacco
                        Mar 24 '10 at 10:08






                      • 1





                        all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                        – Kinjal Dixit
                        Nov 24 '12 at 6:22

















                      thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                      – raki
                      Mar 24 '10 at 6:25







                      thanks Gordon but i cannt use this method because i need to show date in different time zones as the user login from different locations

                      – raki
                      Mar 24 '10 at 6:25















                      @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                      – zerkms
                      Mar 24 '10 at 6:44







                      @raki: so just after user is logged in - set up date_default_timezone_set() with proper user's selected timezone.

                      – zerkms
                      Mar 24 '10 at 6:44















                      that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                      – raki
                      Mar 24 '10 at 6:51





                      that is also not possible.. because.. in the database i need to get the dates in any single timezone, then only it can be processed properly

                      – raki
                      Mar 24 '10 at 6:51




                      8




                      8





                      In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                      – Jacco
                      Mar 24 '10 at 10:08





                      In the database you store everything in GMT. Either that, or it becomes an unmanageable mess.

                      – Jacco
                      Mar 24 '10 at 10:08




                      1




                      1





                      all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                      – Kinjal Dixit
                      Nov 24 '12 at 6:22





                      all this is more complicated than it needs to be. if i set the default timezone, then the date('Y-m-d H:i:s') bit that i do to get the created/updated times will be in the user timezone. So I have to convert them to UTC. Lots of changes everywhere, making sure that i am not doing the conversion twice. This is really an impedance mismatch.

                      – Kinjal Dixit
                      Nov 24 '12 at 6:22













                      14














                      An even simpler method looks like this:



                      date_default_timezone_set('Europe/London'); // your user's timezone
                      $my_datetime='2013-10-23 15:47:10';
                      echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));


                      As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.



                      I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.






                      share|improve this answer




























                        14














                        An even simpler method looks like this:



                        date_default_timezone_set('Europe/London'); // your user's timezone
                        $my_datetime='2013-10-23 15:47:10';
                        echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));


                        As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.



                        I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.






                        share|improve this answer


























                          14












                          14








                          14







                          An even simpler method looks like this:



                          date_default_timezone_set('Europe/London'); // your user's timezone
                          $my_datetime='2013-10-23 15:47:10';
                          echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));


                          As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.



                          I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.






                          share|improve this answer













                          An even simpler method looks like this:



                          date_default_timezone_set('Europe/London'); // your user's timezone
                          $my_datetime='2013-10-23 15:47:10';
                          echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));


                          As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.



                          I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Oct 23 '13 at 15:54









                          sogersoger

                          583514




                          583514























                              11














                              This worked for me and it's pretty clean too!



                              function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                              {
                              try {
                              $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
                              $dateTime->setTimezone(new DateTimeZone($userTimeZone));
                              return $dateTime->format($format);
                              } catch (Exception $e) {
                              return '';
                              }
                              }

                              function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                              {
                              try {
                              $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
                              $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
                              return $dateTime->format($format);
                              } catch (Exception $e) {
                              return '';
                              }
                              }

                              //example usage
                              $serverDate = $userDate = '2014-09-04 22:37:22';
                              echo convert_to_user_date($serverDate);
                              echo convert_to_server_date($userDate);





                              share|improve this answer






























                                11














                                This worked for me and it's pretty clean too!



                                function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                {
                                try {
                                $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
                                $dateTime->setTimezone(new DateTimeZone($userTimeZone));
                                return $dateTime->format($format);
                                } catch (Exception $e) {
                                return '';
                                }
                                }

                                function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                {
                                try {
                                $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
                                $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
                                return $dateTime->format($format);
                                } catch (Exception $e) {
                                return '';
                                }
                                }

                                //example usage
                                $serverDate = $userDate = '2014-09-04 22:37:22';
                                echo convert_to_user_date($serverDate);
                                echo convert_to_server_date($userDate);





                                share|improve this answer




























                                  11












                                  11








                                  11







                                  This worked for me and it's pretty clean too!



                                  function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                  {
                                  try {
                                  $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
                                  $dateTime->setTimezone(new DateTimeZone($userTimeZone));
                                  return $dateTime->format($format);
                                  } catch (Exception $e) {
                                  return '';
                                  }
                                  }

                                  function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                  {
                                  try {
                                  $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
                                  $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
                                  return $dateTime->format($format);
                                  } catch (Exception $e) {
                                  return '';
                                  }
                                  }

                                  //example usage
                                  $serverDate = $userDate = '2014-09-04 22:37:22';
                                  echo convert_to_user_date($serverDate);
                                  echo convert_to_server_date($userDate);





                                  share|improve this answer















                                  This worked for me and it's pretty clean too!



                                  function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                  {
                                  try {
                                  $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
                                  $dateTime->setTimezone(new DateTimeZone($userTimeZone));
                                  return $dateTime->format($format);
                                  } catch (Exception $e) {
                                  return '';
                                  }
                                  }

                                  function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
                                  {
                                  try {
                                  $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
                                  $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
                                  return $dateTime->format($format);
                                  } catch (Exception $e) {
                                  return '';
                                  }
                                  }

                                  //example usage
                                  $serverDate = $userDate = '2014-09-04 22:37:22';
                                  echo convert_to_user_date($serverDate);
                                  echo convert_to_server_date($userDate);






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Sep 5 '14 at 20:54

























                                  answered Jan 30 '14 at 5:58









                                  saadasaada

                                  1,53711927




                                  1,53711927























                                      7














                                      None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.



                                      Here is my solution:



                                      function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
                                      {
                                      if (empty($timeZoneSource)) {
                                      $timeZoneSource = date_default_timezone_get();
                                      }
                                      if (empty($timeZoneTarget)) {
                                      $timeZoneTarget = date_default_timezone_get();
                                      }

                                      $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
                                      $dt->setTimezone(new DateTimeZone($timeZoneTarget));

                                      return $dt->format("Y-m-d H:i:s");
                                      }


                                      So, to convert to the server default, you would just pass one timezone:



                                      changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");


                                      To convert from the server default to the user, you would leave the 2nd parameter null or blank:



                                      changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");


                                      And to switch between to timezones unrelated to the default, you would provide 2 timezones:



                                      changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");





                                      share|improve this answer


























                                      • Seems to work great!

                                        – Adam F
                                        Jan 26 '17 at 21:44






                                      • 1





                                        Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                        – Ajay Singh
                                        Jan 13 '18 at 19:13
















                                      7














                                      None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.



                                      Here is my solution:



                                      function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
                                      {
                                      if (empty($timeZoneSource)) {
                                      $timeZoneSource = date_default_timezone_get();
                                      }
                                      if (empty($timeZoneTarget)) {
                                      $timeZoneTarget = date_default_timezone_get();
                                      }

                                      $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
                                      $dt->setTimezone(new DateTimeZone($timeZoneTarget));

                                      return $dt->format("Y-m-d H:i:s");
                                      }


                                      So, to convert to the server default, you would just pass one timezone:



                                      changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");


                                      To convert from the server default to the user, you would leave the 2nd parameter null or blank:



                                      changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");


                                      And to switch between to timezones unrelated to the default, you would provide 2 timezones:



                                      changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");





                                      share|improve this answer


























                                      • Seems to work great!

                                        – Adam F
                                        Jan 26 '17 at 21:44






                                      • 1





                                        Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                        – Ajay Singh
                                        Jan 13 '18 at 19:13














                                      7












                                      7








                                      7







                                      None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.



                                      Here is my solution:



                                      function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
                                      {
                                      if (empty($timeZoneSource)) {
                                      $timeZoneSource = date_default_timezone_get();
                                      }
                                      if (empty($timeZoneTarget)) {
                                      $timeZoneTarget = date_default_timezone_get();
                                      }

                                      $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
                                      $dt->setTimezone(new DateTimeZone($timeZoneTarget));

                                      return $dt->format("Y-m-d H:i:s");
                                      }


                                      So, to convert to the server default, you would just pass one timezone:



                                      changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");


                                      To convert from the server default to the user, you would leave the 2nd parameter null or blank:



                                      changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");


                                      And to switch between to timezones unrelated to the default, you would provide 2 timezones:



                                      changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");





                                      share|improve this answer















                                      None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.



                                      Here is my solution:



                                      function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
                                      {
                                      if (empty($timeZoneSource)) {
                                      $timeZoneSource = date_default_timezone_get();
                                      }
                                      if (empty($timeZoneTarget)) {
                                      $timeZoneTarget = date_default_timezone_get();
                                      }

                                      $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
                                      $dt->setTimezone(new DateTimeZone($timeZoneTarget));

                                      return $dt->format("Y-m-d H:i:s");
                                      }


                                      So, to convert to the server default, you would just pass one timezone:



                                      changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");


                                      To convert from the server default to the user, you would leave the 2nd parameter null or blank:



                                      changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");


                                      And to switch between to timezones unrelated to the default, you would provide 2 timezones:



                                      changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Dec 12 '16 at 16:58

























                                      answered Oct 24 '16 at 7:33









                                      SkeetsSkeets

                                      1,5761331




                                      1,5761331













                                      • Seems to work great!

                                        – Adam F
                                        Jan 26 '17 at 21:44






                                      • 1





                                        Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                        – Ajay Singh
                                        Jan 13 '18 at 19:13



















                                      • Seems to work great!

                                        – Adam F
                                        Jan 26 '17 at 21:44






                                      • 1





                                        Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                        – Ajay Singh
                                        Jan 13 '18 at 19:13

















                                      Seems to work great!

                                      – Adam F
                                      Jan 26 '17 at 21:44





                                      Seems to work great!

                                      – Adam F
                                      Jan 26 '17 at 21:44




                                      1




                                      1





                                      Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                      – Ajay Singh
                                      Jan 13 '18 at 19:13





                                      Nice answer. I prefer try catch instead of is(empty) to avoid any spelling errors in timezone string. try{ new DateTimeZone($timeZoneSource); } catch(Exception $e){ $timeZoneSource = date_default_timezone_get(); }

                                      – Ajay Singh
                                      Jan 13 '18 at 19:13











                                      5














                                      DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object



                                      Object oriented style



                                      <?php
                                      $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
                                      echo $date->format('Y-m-d H:i:sP') . "n";

                                      $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
                                      echo $date->format('Y-m-d H:i:sP') . "n";
                                      ?>


                                      Procedural style



                                      <?php
                                      $date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
                                      echo date_format($date, 'Y-m-d H:i:sP') . "n";

                                      date_timezone_set($date, timezone_open('Pacific/Chatham'));
                                      echo date_format($date, 'Y-m-d H:i:sP') . "n";
                                      ?>


                                      The above examples will output:



                                      2000-01-01 00:00:00+12:00
                                      2000-01-01 01:45:00+13:45





                                      share|improve this answer




























                                        5














                                        DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object



                                        Object oriented style



                                        <?php
                                        $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
                                        echo $date->format('Y-m-d H:i:sP') . "n";

                                        $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
                                        echo $date->format('Y-m-d H:i:sP') . "n";
                                        ?>


                                        Procedural style



                                        <?php
                                        $date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
                                        echo date_format($date, 'Y-m-d H:i:sP') . "n";

                                        date_timezone_set($date, timezone_open('Pacific/Chatham'));
                                        echo date_format($date, 'Y-m-d H:i:sP') . "n";
                                        ?>


                                        The above examples will output:



                                        2000-01-01 00:00:00+12:00
                                        2000-01-01 01:45:00+13:45





                                        share|improve this answer


























                                          5












                                          5








                                          5







                                          DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object



                                          Object oriented style



                                          <?php
                                          $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
                                          echo $date->format('Y-m-d H:i:sP') . "n";

                                          $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
                                          echo $date->format('Y-m-d H:i:sP') . "n";
                                          ?>


                                          Procedural style



                                          <?php
                                          $date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
                                          echo date_format($date, 'Y-m-d H:i:sP') . "n";

                                          date_timezone_set($date, timezone_open('Pacific/Chatham'));
                                          echo date_format($date, 'Y-m-d H:i:sP') . "n";
                                          ?>


                                          The above examples will output:



                                          2000-01-01 00:00:00+12:00
                                          2000-01-01 01:45:00+13:45





                                          share|improve this answer













                                          DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object



                                          Object oriented style



                                          <?php
                                          $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
                                          echo $date->format('Y-m-d H:i:sP') . "n";

                                          $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
                                          echo $date->format('Y-m-d H:i:sP') . "n";
                                          ?>


                                          Procedural style



                                          <?php
                                          $date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
                                          echo date_format($date, 'Y-m-d H:i:sP') . "n";

                                          date_timezone_set($date, timezone_open('Pacific/Chatham'));
                                          echo date_format($date, 'Y-m-d H:i:sP') . "n";
                                          ?>


                                          The above examples will output:



                                          2000-01-01 00:00:00+12:00
                                          2000-01-01 01:45:00+13:45






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jul 4 '14 at 12:14









                                          itsazzaditsazzad

                                          3,50644263




                                          3,50644263























                                              3














                                              UTC to local:



                                              <?php
                                              $datetime = date("Y-m-d H:i:s");
                                              $utc = new DateTime($datetime, new DateTimeZone('UTC'));
                                              $utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
                                              echo $utc->format('Y-m-d H:i:s');

                                              ?>





                                              share|improve this answer






























                                                3














                                                UTC to local:



                                                <?php
                                                $datetime = date("Y-m-d H:i:s");
                                                $utc = new DateTime($datetime, new DateTimeZone('UTC'));
                                                $utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
                                                echo $utc->format('Y-m-d H:i:s');

                                                ?>





                                                share|improve this answer




























                                                  3












                                                  3








                                                  3







                                                  UTC to local:



                                                  <?php
                                                  $datetime = date("Y-m-d H:i:s");
                                                  $utc = new DateTime($datetime, new DateTimeZone('UTC'));
                                                  $utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
                                                  echo $utc->format('Y-m-d H:i:s');

                                                  ?>





                                                  share|improve this answer















                                                  UTC to local:



                                                  <?php
                                                  $datetime = date("Y-m-d H:i:s");
                                                  $utc = new DateTime($datetime, new DateTimeZone('UTC'));
                                                  $utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
                                                  echo $utc->format('Y-m-d H:i:s');

                                                  ?>






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Sep 30 '16 at 17:29

























                                                  answered Jul 26 '16 at 11:24









                                                  Eduardo MarcolinoEduardo Marcolino

                                                  293




                                                  293























                                                      1














                                                      // Convert date from one zone to another..
                                                      /*
                                                      $zone_from='Asia/Kolkata';



                                                      $zone_to='America/Phoenix';

                                                      date_default_timezone_set($zone_from);

                                                      $convert_date="2016-02-26 10:35:00";

                                                      echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);

                                                      */
                                                      function zone_conversion_date($time, $cur_zone, $req_zone)
                                                      {
                                                      date_default_timezone_set("GMT");
                                                      $gmt = date("Y-m-d H:i:s");

                                                      date_default_timezone_set($cur_zone);
                                                      $local = date("Y-m-d H:i:s");

                                                      date_default_timezone_set($req_zone);
                                                      $required = date("Y-m-d H:i:s");

                                                      /* return $required; */
                                                      $diff1 = (strtotime($gmt) - strtotime($local));
                                                      $diff2 = (strtotime($required) - strtotime($gmt));

                                                      $date = new DateTime($time);
                                                      $date->modify("+$diff1 seconds");
                                                      $date->modify("+$diff2 seconds");

                                                      return $timestamp = $date->format("Y-m-d H:i:s");
                                                      }





                                                      share|improve this answer




























                                                        1














                                                        // Convert date from one zone to another..
                                                        /*
                                                        $zone_from='Asia/Kolkata';



                                                        $zone_to='America/Phoenix';

                                                        date_default_timezone_set($zone_from);

                                                        $convert_date="2016-02-26 10:35:00";

                                                        echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);

                                                        */
                                                        function zone_conversion_date($time, $cur_zone, $req_zone)
                                                        {
                                                        date_default_timezone_set("GMT");
                                                        $gmt = date("Y-m-d H:i:s");

                                                        date_default_timezone_set($cur_zone);
                                                        $local = date("Y-m-d H:i:s");

                                                        date_default_timezone_set($req_zone);
                                                        $required = date("Y-m-d H:i:s");

                                                        /* return $required; */
                                                        $diff1 = (strtotime($gmt) - strtotime($local));
                                                        $diff2 = (strtotime($required) - strtotime($gmt));

                                                        $date = new DateTime($time);
                                                        $date->modify("+$diff1 seconds");
                                                        $date->modify("+$diff2 seconds");

                                                        return $timestamp = $date->format("Y-m-d H:i:s");
                                                        }





                                                        share|improve this answer


























                                                          1












                                                          1








                                                          1







                                                          // Convert date from one zone to another..
                                                          /*
                                                          $zone_from='Asia/Kolkata';



                                                          $zone_to='America/Phoenix';

                                                          date_default_timezone_set($zone_from);

                                                          $convert_date="2016-02-26 10:35:00";

                                                          echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);

                                                          */
                                                          function zone_conversion_date($time, $cur_zone, $req_zone)
                                                          {
                                                          date_default_timezone_set("GMT");
                                                          $gmt = date("Y-m-d H:i:s");

                                                          date_default_timezone_set($cur_zone);
                                                          $local = date("Y-m-d H:i:s");

                                                          date_default_timezone_set($req_zone);
                                                          $required = date("Y-m-d H:i:s");

                                                          /* return $required; */
                                                          $diff1 = (strtotime($gmt) - strtotime($local));
                                                          $diff2 = (strtotime($required) - strtotime($gmt));

                                                          $date = new DateTime($time);
                                                          $date->modify("+$diff1 seconds");
                                                          $date->modify("+$diff2 seconds");

                                                          return $timestamp = $date->format("Y-m-d H:i:s");
                                                          }





                                                          share|improve this answer













                                                          // Convert date from one zone to another..
                                                          /*
                                                          $zone_from='Asia/Kolkata';



                                                          $zone_to='America/Phoenix';

                                                          date_default_timezone_set($zone_from);

                                                          $convert_date="2016-02-26 10:35:00";

                                                          echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);

                                                          */
                                                          function zone_conversion_date($time, $cur_zone, $req_zone)
                                                          {
                                                          date_default_timezone_set("GMT");
                                                          $gmt = date("Y-m-d H:i:s");

                                                          date_default_timezone_set($cur_zone);
                                                          $local = date("Y-m-d H:i:s");

                                                          date_default_timezone_set($req_zone);
                                                          $required = date("Y-m-d H:i:s");

                                                          /* return $required; */
                                                          $diff1 = (strtotime($gmt) - strtotime($local));
                                                          $diff2 = (strtotime($required) - strtotime($gmt));

                                                          $date = new DateTime($time);
                                                          $date->modify("+$diff1 seconds");
                                                          $date->modify("+$diff2 seconds");

                                                          return $timestamp = $date->format("Y-m-d H:i:s");
                                                          }






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Feb 26 '16 at 5:21









                                                          user2801665user2801665

                                                          8713




                                                          8713























                                                              0














                                                              <?php
                                                              $time='6:02';
                                                              $dt = new DateTime($time, new DateTimeZone('America/New_York'));
                                                              //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
                                                              $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                                              echo $dt->format('H:i') . PHP_EOL;
                                                              ?>





                                                              share|improve this answer




























                                                                0














                                                                <?php
                                                                $time='6:02';
                                                                $dt = new DateTime($time, new DateTimeZone('America/New_York'));
                                                                //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
                                                                $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                                                echo $dt->format('H:i') . PHP_EOL;
                                                                ?>





                                                                share|improve this answer


























                                                                  0












                                                                  0








                                                                  0







                                                                  <?php
                                                                  $time='6:02';
                                                                  $dt = new DateTime($time, new DateTimeZone('America/New_York'));
                                                                  //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
                                                                  $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                                                  echo $dt->format('H:i') . PHP_EOL;
                                                                  ?>





                                                                  share|improve this answer













                                                                  <?php
                                                                  $time='6:02';
                                                                  $dt = new DateTime($time, new DateTimeZone('America/New_York'));
                                                                  //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
                                                                  $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                                                  echo $dt->format('H:i') . PHP_EOL;
                                                                  ?>






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Oct 12 '15 at 10:22









                                                                  Hara PrasadHara Prasad

                                                                  426410




                                                                  426410






























                                                                      draft saved

                                                                      draft discarded




















































                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid



                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                      To learn more, see our tips on writing great answers.




                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function () {
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2505681%2ftimezone-conversion-in-php%23new-answer', 'question_page');
                                                                      }
                                                                      );

                                                                      Post as a guest















                                                                      Required, but never shown





















































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown

































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown







                                                                      這個網誌中的熱門文章

                                                                      Xamarin.form Move up view when keyboard appear

                                                                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                                      Anylogic : not able to use stopDelay()