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

这怎么可能呢?


当前回答

有两种实现方法:

1.

    $date = strtotime(date);
    $new_date = date('d-m-Y', $date);

2.

    $cls_date = new DateTime($date);
    echo $cls_date->format('d-m-Y');

其他回答

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

$date = '9/18/2019';

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

结果:

The 18-09-19

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

在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));

使用此函数可以从任何格式转换为任何格式

function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}

如果你想避免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
?>