简体   繁体   中英

PHP Timestamp Hour issue

Currently I'm creating a website that also creates logs. The problem is, is the time stamps. Everything but the Hour is reading correctly.

Code:

$date = date('Y-m-d, g:i:s a');
$sql = "INSERT INTO logs (ip, date, page) VALUES ('$ip', '$date', '$page')";

Currently it is 6:41 PM and this is what its reading (The minutes and seconds are accurate)

在此处输入图片说明

try this...

// you need to find your timezone here: http://php.net/manual/en/timezones.php
$timezone = new DateTimeZone('America/New_York'); 

$date_obj = new DateTime("now", $timezone); 
$date_obj->setTimezone(new DateTimeZone('UTC'));

$date = $date_obj->format('Y-m-d H:i:s');  

$sql = "INSERT INTO logs (ip, date, page) VALUES ('$ip', '$date', '$page')";
print $sql;

More on DateTime

You should really store dates as a datetime and not a string... Also, I would highly consider storing all dates as UTC, too. This way, you always know exactly when something was done and it's not relative. You can display the date back to the user in whatever timezone is appropriate. If you want to make both of those chages, your query would turn into:

$sql = "INSERT INTO logs (ip, date, page) VALUES ('$ip', UTC_TIMESTAMP(), '$page')";

Also, please note that with the other solutio posted here... getdate() is not a MySQL function, it is exclusively for SQL Server. And if you include the quotes around any function name, MySQL will interpret the whole thing as a string and not a function.

I've read that date() is deprecated.

So, I personaly use strftime().

eg to get a time with micro second stamp:

<?php
  echo "Hello world!<br/>";
  echo "We are the ".strftime("%d %B %Y")."<br/>";
  echo "and it is now ".strftime("%I:%M:%S %p")." and ".(float)microtime()." ms.<br/>";
?>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM