0

I am having an issue with php date() function.

When I save the date in mysql datebase the hours shows 4 hours less than my current time.

My php code is below: $add_date = date("Y-m-d H:i:s");

It saves the time in database as

2011-08-03 07:51:26

But is should show

2011-08-03 13:22:26

Can anybody tell me how to fix it

Thanks

2
  • When I run this code I get: 2011-08-03 08:24:27 Commented Aug 3, 2011 at 8:24
  • 1
    When I run it I get 2011-08-03 04:33:02. Funny how time keeps changing and isn't the same in different time zones. Commented Aug 3, 2011 at 8:33

4 Answers 4

3

You have to set a valid time zone - it seems you don't have an appropriate time zone set up in php environment for your location.

Check out

http://www.php.net/manual/en/function.date-default-timezone-set.php

It should give you a clue how to set up the correct time zone in php.

Sign up to request clarification or add additional context in comments.

2 Comments

@Mujahid This is likely to be the problem. You should try to echo the date value before storing it in the MySql database, if they match then it's definitely a timezone problem.
@Saad Imran: when I print the time it just give me the same answer :(
2

@Mujahid If the printed time and the saved time are the same it probably means your server is not in the same timezone as you. With that said, you have to manually set the default timezone for your PHP script at the top of the file, or get the DateTime by defining your timezone explicitly. Here's the code:

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

Here's a list of time zones that PHP supports, just find yours and replace America/Los_Angeles with it.

http://php.net/manual/en/timezones.php

Here's a good tutorial on PHP DateTime and DateTimeZone...

http://ditio.net/2008/06/03/php-datetime-and-datetimezone-tutorial/

Hope this helps. Good luck.

Comments

0

Make the time zone setting of the MySQL server and the web server the same.

3 Comments

Where do you know that the time is not stored in a varchar field?
How do you know the time is not stored in a BLOB? Your question is not constructive.
Sorry, I did not want to fight you. I wanted to clarify the relation to mysql. I first was thinking that OP adds the time string from PHP to the data base. But just have discovered the tag "datetime". So your answer is probably the right one here.
0

this will add hosted server time not local time $add_date = date("Y-m-d H:i:s");

use strtotime() to add hours and minutes

$newdate = date("Y-m-d H:i:s",strtotime('+ 5 hours 30 minutes'.$row['db_date']));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.