XCode Beginner
XCode Beginner

Reputation: 21

PHP date() function not giving correct time

I am trying to figure out why php date() is giving me the wrong time, setting the actual time back 2 hours.

<?php echo date("Y-m-d H:i:s"); ?>

This gives 2011-01-01 03:14:04 instead of 2011-01-01 05:14:04. The hour is decreased by 2. I have not change my timezone for date() and when users visit the site I want the time to be correct for their timezone also. How can I get this to work using php?

Upvotes: 1

Views: 20083

Answers (4)

Hassan Saeed
Hassan Saeed

Reputation: 7080

it is because by default it shows GMT time you can change for your region with following code

   date_default_timezone_set("Asia/Bangkok");//set you countary name from below timezone list
    echo $date = date("Y-m-d H:i:s", time());//now it will show "Asia/Bangkok" or your date time

List of Supported Timezones http://www.php.net/manual/en/timezones.php

Upvotes: 3

Shal
Shal

Reputation: 633

//Change date format

$dateInfo = date_parse_from_format('m-d-Y', $data['post_date']);
$unixTimestamp = mktime(
        $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
        $dateInfo['month'], $dateInfo['day'], $dateInfo['year']
    );
$data['post_date']=date('Y-m-d',$unixTimestamp);

Upvotes: 0

Teej
Teej

Reputation: 12873

Try setting the the timezone: date_default_timezone_set or via the ini

Update: you cannot set the correct date for your users. Javascript can handle it but you'd have to rely on the user's system to determine his/her time.

Upvotes: 1

Phoenix
Phoenix

Reputation: 4536

You would have to use either date_default_timezone_set() or a datetime object, and the user would have to set their own timezone in an options menu somewhere.

Otherwise, PHP is a server side language and has no idea what time it is on the user's end.

You would have to use a client side language, JavaScript. You could either have it just be static and display the current user system time, or if for whatever reason you needed to get their time into PHP, you could use some AJAX like scripting to have JavaScript send their time into a script when the page loads.

Upvotes: 2

Related Questions