我有一个采用这种格式的日期:2014 年 5 月 21 日星期三。
\n\n要将此日期保存在数据库中,我尝试将其转换为日期时间,如下所示:
\n\n$f[\'date\'] = $_POST[\'date\'];\n$date = DateTime::createFromFormat(\'l, j F, Y\', $f[\'date\']); \n$date = $data->format(\'Y-m-d H:i:s\'); \nRun Code Online (Sandbox Code Playgroud)\n\n然后我\xc2\xb4ll在我的数据库中插入$date,并且工作正常,日期像数据库中的日期时间一样保存。
\n\n但现在我想显示日期,所以我想再次转换它,格式如下:“Wednesday, 21 May, 2014”。
\n\n为此,我进行选择,然后再次使用 DateTime::createFormat 将日期从日期时间转换为我的“文本格式”:
\n\n$readNews = $pdo->prepare("SELECT * FROM news");\n$readNews->execute();\nwhile ($readNewsResult = $readNews->fetch(PDO::FETCH_ASSOC))\n{\n $date = DateTime::createFromFormat(\'l, j F, Y\', $readNewsResult[\'date\']);\n ..... //here I have more echos showing title of the news, etc\n echo \'<span class="date">\'.$date.\'</span>\';\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我遇到的问题是它没有 \xc2\xb4t 出现的日期......
\n\n你看到我在这里做错了什么吗?
\n你不需要DateTime::createFromFormat()这里。DateTime::createFromFormat()仅当您的日期格式为 PHP 无法理解时才需要使用。您已经有了可以处理的格式DateTime()。
因此,您需要做的就是在打印时更改您将使用的格式DateTime::format():
$date = new DateTime($readNewsResult['date']);
echo '<span class="date">'.$date->format('l, j F, Y').'</span>';
Run Code Online (Sandbox Code Playgroud)