简体   繁体   English

PHP时间戳小时问题

[英]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) 当前是下午6:41,这是它的读数(分钟和秒是准确的)

在此处输入图片说明

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 有关DateTime的更多信息

You should really store dates as a datetime and not a string... Also, I would highly consider storing all dates as UTC, too. 您实际上应该将日期存储为日期时间而不是字符串。。此外,我也极力考虑将所有日期存储为UTC。 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. 另外,请注意,此处发布了其他解决方案... getdate() 不是 MySQL函数,它仅用于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. 并且,如果在任何函数名称周围加上引号,MySQL会将整个内容解释为字符串而不是函数。

I've read that date() is deprecated. 我已经阅读过date()已过时。

So, I personaly use strftime(). 因此,我个人使用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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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