我看到这个问题被多次询问,但我有一些额外的因素,我认为答案没有考虑到。
这是场景。我在表格中存储了一些日期(目前在varchar中)。现在是将这些日期转换为日期时间并将所有未来日期妥善保存的时候了。来自newsapi.org,我收到文章(标题,描述和日期,格式为2017-05-03T00:48:09Z)
两个问题: 我可以执行哪些SQL代码将此列字符串转换为日期时间?
编辑: 我试过这个,但是我收到了一个错误。我甚至编辑了我的php.ini文件
MariaDB [default]> UPDATE News SET ts=CAST(publishedAt AS TIMESTAMP);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'TIMESTAMP)' at line 1
什么样的php允许我采用这样的字符串并将其正确地放入“插入”语句中?
编辑 当试图运行Ahmed Ginani回答时我得到了这个错误
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in /var/www/html/news/news.php:32 Stack trace: #0 /var/www/html/news/news.php(32): DateTime->__construct('2017-05-10T18:0...') #1 {main} thrown in /var/www/html/news/news.php on line 32
使用
foreach ($obj->articles as &$article)
{
$title = htmlspecialchars($article->title, ENT_QUOTES);
$author = htmlspecialchars($article->author, ENT_QUOTES);
$description = htmlspecialchars($article->description, ENT_QUOTES);
$url = htmlspecialchars($article->url, ENT_QUOTES);
$urlToImage = htmlspecialchars($article->urlToImage, ENT_QUOTES);
$date = (new DateTime($article->publishedAt))->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
$sql = "INSERT IGNORE INTO News (author, title, description, url, urlToImage, ts) VALUES ('" . $title . "', '" . $author . "', '" . $description . "', '" . $url . "', '" . $urlToImage . "', $date)";
if($conn->query($sql) === TRUE)
{
echo "New Record Successfuly Created <br>";
}
else
{
echo "Error: " . $conn->error;
echo "<br><br>";
}
}
$conn->close();
答案 0 :(得分:1)
这不起作用吗?
select CAST('2017-05-03T00:48:09Z' AS TIMESTAMP);
适用于所有符合ISO / ANSI标准的数据库......
显然,MariaDB不能CAST()到TIMESTAMP类型...... 然后,使用此处的文档:https://mariadb.com/kb/en/mariadb/str_to_date/,试试这个:
SELECT STR_TO_DATE(publishedAt,'%Y-%m-%dT%H:%i:%sZ');
在这里,我假设格式为:2017-05-03T23:48:09Z
有效:24小时时间描述。
答案 1 :(得分:1)
尝试以下代码
注意&#39; Z&#39;最后这意味着祖鲁(a.k.a UTC)因此可能值得将您的日期和时间转换为UTC,如下所示:
<?php
$date = (new DateTime('2017-05-03T00:48:09Z'))->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
?>