How to get local time in php?

前端 未结 7 1265
野性不改
野性不改 2021-02-02 03:12

I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time

date_default_timezone_set(\'UTC\');
$now = new Dat         


        
相关标签:
7条回答
  • 2021-02-02 03:47

    You can solve this problem by using localtime() function or through date_default_timezone_set() function.

    Learn more about the localtime() function reffer:
    http://php.net/manual/en/function.localtime.php

    or

    Learn more about the date_default_timezone_set() function reffer http://www.php.net/manual/en/function.date-default-timezone-set.php

    i think this must help you..

    0 讨论(0)
  • 2021-02-02 03:49

    If you don't want to use timezone you can use this mix of windows and php commands:

    <?php 
      $D = exec('date /T');
      $T = exec('time /T');
      $DT = strtotime(str_replace("/","-",$D." ".$T));
      echo(date("Y-m-d H:i:s",$DT));
    ?>
    
    0 讨论(0)
  • 2021-02-02 03:51

    You need to use javascript because you want the value of time from the client. PHP is a server-side language that evaluates on the server and sends results to the client. So if you try to pull a date/time using a PHP function, it's going to pull the date from the server, which is not always in the client's timezone.

    You can do this in a javascript function and then reference the value in the display.

    var thisDateTime = new Date();

    0 讨论(0)
  • 2021-02-02 03:55

    DateTime::getTimestamp() returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.

    $dt = new DateTime("now", new DateTimeZone('America/New York'));
    
    echo $dt->format('m/d/Y, H:i:s');
    

    Or use a different date format, according to what you need.

    Also, you can use DateTime library for all your date needs. No need to change server's default timezone every time you want to fetch the date.

    0 讨论(0)
  • 2021-02-02 03:56

    For the record, I found the only solution to read the real hour of the machine is to read the information outside of PHP (javascript, shell or other processes). Why?

    For example, let's say we have an hour based in daily-saving. What if the timezone of the OS (Windows in my case) is not in sync with the timezone of PHP, I mean, it could be calculated differently. Or maybe the machine is using a different hour and it is ignoring the daily-saving hour.

    Right now, my zone is UTC -4 Santiago 9:35 pm (with daily saving). However, PHP considers as 10:35 PM (using localtime,time,date and DateTime).

    0 讨论(0)
  • 2021-02-02 04:01

    I'm wondering why nobody has mentioned localtime(time()); in PHP with indexed key array result or localtime(time(), true); with associative key array result.

    0 讨论(0)
提交回复
热议问题