php date() gives me wrong time when executed.

Discussion in 'Off Topic' started by ChatIndia, Mar 11, 2013.

  1. ChatIndia

    ChatIndia Community Advocate Community Support

    Messages:
    1,408
    Likes Received:
    30
    Trophy Points:
    48
    Code:
    <?php
    $var = date('l jS \of F Y h:i:s A');
    echo $var;
    ?>
    
    My system time is 9:33 PM while I get

    Monday 11th of March 2013 05:03:16 PM

    please help me understand the problem. i am just starting with php.
     
  2. ChatIndia

    ChatIndia Community Advocate Community Support

    Messages:
    1,408
    Likes Received:
    30
    Trophy Points:
    48
    maybe the above code is too confusing. So here is the simple one.
    Code:
    <?php
    $var = date('H');
    echo $var;
    ?>
    
    I get 17 instead of 21.
     
    Last edited: Mar 11, 2013
  3. essellar

    essellar Community Advocate Community Support

    Messages:
    3,295
    Likes Received:
    227
    Trophy Points:
    63
    It's probably a time zone problem. PHP does all of its date/time calculations based on time stamps (number of seconds since the Unix epoch, January 1 1970 00:00:00 GMT), and will be quite happy to work strictly in UTC/GMT until you tell it otherwise. The default value for date.timezone in the php.ini file is UTC . You can modify that if you have control of the machine and can alter the php.ini, but it's generally safer (even for development on a local machine) to leave the default value alone and use the date_default_timezone_set() function in your code. Not only does that ensure that your code works properly no matter what the php.ini setting is on the server that's running it, it also allows you to get the user's time local time zone and use that when generating the page, either using a user-set preference, JavaScript (using the getTimezoneOffset() method of the Date object or a library like jsTimezoneDetect; see https://bitbucket.org/pellepim/jstimezonedetect ) or geolocation (based on the user's IP address and request accept_language headers).

    It is certainly simplest to say "this site's dates and times are in X time zone", put that value in a call to date_default_timezone_set() on your "include everywhere" header script and leave it at that. But you do need to do something if you want the times in anything other than GMT.
     
  4. ChatIndia

    ChatIndia Community Advocate Community Support

    Messages:
    1,408
    Likes Received:
    30
    Trophy Points:
    48

Share This Page