我试图将日期从yyyy-mm-dd转换为dd-mm-yyyy(但不是SQL);然而,我不知道日期函数如何需要时间戳,我无法从这个字符串中获得时间戳。
这怎么可能呢?
我试图将日期从yyyy-mm-dd转换为dd-mm-yyyy(但不是SQL);然而,我不知道日期函数如何需要时间戳,我无法从这个字符串中获得时间戳。
这怎么可能呢?
当前回答
Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes. Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD". Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.
投票最多的答案其实是错误的!
PHP strtotime手册在这里声明“该函数期望得到一个包含英文日期格式的字符串”。它实际上的意思是,它期望美国日期格式,如“m-d-Y”或“m/d/Y”。
这意味着以“Y-m-d”形式提供的日期可能会被strtotime错误解释。您应该以预期的格式提供日期。
我写了一个小函数,以几种格式返回日期。随意使用和修改。如果有人真的把它变成了一个类,我很高兴它能被分享。
function Date_Converter($date, $locale = "br") {
# Exception
if (is_null($date))
$date = date("m/d/Y H:i:s");
# Let's go ahead and get a string date in case we've
# been given a Unix Time Stamp
if ($locale == "unix")
$date = date("m/d/Y H:i:s", $date);
# Separate Date from Time
$date = explode(" ", $date);
if ($locale == "br") {
# Separate d/m/Y from Date
$date[0] = explode("/", $date[0]);
# Rearrange Date into m/d/Y
$date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
}
# Return date in all formats
# US
$Return["datetime"]["us"] = implode(" ", $date);
$Return["date"]["us"] = $date[0];
# Universal
$Return["time"] = $date[1];
$Return["unix_datetime"] = strtotime($Return["datetime"]["us"]);
$Return["unix_date"] = strtotime($Return["date"]["us"]);
$Return["getdate"] = getdate($Return["unix_datetime"]);
# BR
$Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
$Return["date"]["br"] = date("d/m/Y", $Return["unix_date"]);
# Return
return $Return;
} # End Function
其他回答
对于这种特定的转换,我们还可以使用格式字符串。
$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));
显然,这不适用于许多其他日期格式转换,但由于我们在本例中只是重新排列子字符串,因此这是另一种可能的方法。
在PHP中,任何日期都可以转换为所需的日期格式,使用不同的场景,例如将任何日期格式转换为 日、日、月、年
$newdate = date("D, d M Y", strtotime($date));
它将以以下非常好的格式显示日期
2020年11月16日星期一
$timestamp = strtotime(your date variable);
$new_date = date('d-m-Y', $timestamp);
有关更多信息,请参阅strtotime的文档。
或者更短:
$new_date = date('d-m-Y', strtotime(your date variable));
使用strtotime()和date():
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
(请参阅PHP站点上的strtotime和date文档。)
请注意,这是原始问题的快速解决方案。对于更广泛的转换,你应该使用DateTime类来解析和格式化:-)
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);
此代码适用于所有日期格式。
由于您的旧日期格式,您可以更改替换变量的顺序,例如$3-$1-$2。