我试图将日期从yyyy-mm-dd转换为dd-mm-yyyy(但不是SQL);然而,我不知道日期函数如何需要时间戳,我无法从这个字符串中获得时间戳。

这怎么可能呢?


当前回答

如果你想避免strtotime转换(例如,strtotime不能解析你的输入),你可以使用,

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');

或者,相当于:

$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');

你首先给它$dateString的格式。然后你告诉它你想要的$newDateString的格式。

或者如果source-format总是“Y-m-d”(yyyy-mm-dd),那么只需使用DateTime:

<?php
    $source = '2012-07-31';
    $date = new DateTime($source);
    echo $date->format('d.m.Y'); // 31.07.2012
    echo $date->format('d-m-Y'); // 31-07-2012
?>

其他回答

对于这种特定的转换,我们还可以使用格式字符串。

$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));

显然,这不适用于许多其他日期格式转换,但由于我们在本例中只是重新排列子字符串,因此这是另一种可能的方法。

使用date_create和date_format

试试这个。

function formatDate($input, $output){
  $inputdate = date_create($input);
  $output = date_format($inputdate, $output);
  return $output;
}
date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));

您可以使用date()和strtotime()更改格式。

$date = '9/18/2019';

echo(’d-m-y’日期、strtotime(美元);

结果:

The 18-09-19

我们可以通过改变(d-m-y)来改变格式。

下面给出的PHP代码使用mktime()生成明天的日期,并将其格式更改为dd/mm/yyyy格式,然后使用echo打印它。

$tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);