如果我有一个mm-dd-YYYY
格式的PHP字符串(例如,10-16-2003),我如何正确地将其转换为Date
然后DateTime
格式为YYYY-mm-dd
?我要求Date
和DateTime
的唯一原因是因为我需要一个在一个地方,另一个在另一个地方。
在你的第一个日期使用strtotime()
然后date('Y-m-d')
将其转换回来:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
请注意,在/
函数中使用正斜杠-
和hyphen strtotime()
之间存在差异。引用php.net:
通过查看各个组件之间的分隔符来消除m / d / y或d-m-y格式的日期:如果分隔符是斜杠(/),则假设为美国m / d / y;而如果分隔符是破折号( - )或点(。),则假定为欧洲d-m-y格式。
您需要注意m / d / Y和m-d-Y格式。 PHP认为/
表示m / d / Y,-
表示d-m-Y。在这种情况下,我会明确描述输入格式:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
这样你就不会有某种解释的心血来潮。
要解析日期,您应该使用:DateTime :: createFromFormat();
例如:
$dateDE = "16/10/2013";
$dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
但是,小心,因为这会崩溃:
PHP Fatal error: Call to a member function format() on a non-object
你实际上需要检查格式是否正常,首先:
$dateDE = "16/10/2013";
$dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
if (!$dateObj)
{
throw new \UnexpectedValueException("Could not parse the date: $date");
}
$dateUS = $dateObj->format("m/d/Y");
现在,您将获得一个异常,而不是崩溃,您可以捕获,传播等。
$ dateDE格式错误,应为“16.10.2013”;
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
编辑:您还可以将DateTimeZone传递给DateTime()构造函数,以确保创建所需时区的日期,而不是服务器默认日期。
如果您的格式为dd-mm-yyyy,那么在PHP中它将无法按预期工作。在PHP文档中,他们有以下指南。
通过查看各个组件之间的分隔符来消除m / d / y或d-m-y格式的日期:如果分隔符是斜杠(/),则假设为美国m / d / y;而如果分隔符是破折号( - )或点(。),则假定为欧洲d-m-y格式。
所以,你根本无法使用。当您尝试使用dd / mm / yyyy格式时,它将删除FALSE。您可以使用以下内容进行调整。
$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600
对于第一个日期
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
对于新日期
$_newDate = date("Y-m-d",strtotime($_yourDateString));
就像我们有日期“07 / May / 2018”,我们需要日期“2018-05-07”作为mysql兼容
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
这个对我有用。请享用 :)
由于没有人提到这一点,这是另一种方式:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
如果您希望使用美式订购(月,日,年)接受欧式样式的日期(使用短划线或句点作为日,月,年),同时仍接受其他格式,则可以扩展DateTime类:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
或者,您可以创建一个函数来接受m-d-Y并输出Y-m-d:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* @param string $d various representations of date
* @return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>