如果我有一个格式为mm-dd-YYYY的PHP字符串(例如,10-16-2003),我如何正确地将其转换为日期,然后是YYYY-mm-dd格式的日期时间?我同时要求Date和DateTime的唯一原因是,我需要一个在一个地方,另一个在不同的地方。


当前回答

我尝试了上面所有的答案,但失败了,在我的情况下,我构建了一个函数,获得以下格式“YYYY/mm/dd”的日期字符串。所以我认为像这样爆炸弦会更好:

$old_date = explode('/', $coming_date_str);

new_data =美元old_date old_date美元[0]。”——“。[1],”——“。美元old_date [2];//将字符串转换为上述所有帖子并完成

$new_date = date('Y-m-d', strtotime($new_data));
$new_date = DateTime::createFromFormat("Y-m-d", new_date);

其他回答

要解析日期,你应该使用: DateTime: createFromFormat ();

Ex:

$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”;

如果你希望接受日期使用美式排序(月,日,年)的欧式格式(使用破折号或句号作为日,月,年),同时仍然接受其他格式,你可以扩展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'); ?>

如果您想获取当月的最后一天,可以使用以下代码。

$last_day_this_month  = date('F jS Y', strtotime(date('F t Y')));

从任意字符串中创建日期:

$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00');
echo $date->format('Y-m-d H:i');

第一次约会

$_firstDate = date("m-d-Y", strtotime($_yourDateString));

新日期

$_newDate = date("Y-m-d",strtotime($_yourDateString));