如何从格式为 DD-MM-YYYY 的日期字符串中获取日、日和年


How to get Day,Date and Year from a date string in the format DD-MM-YYYY

我有一个格式为 DD-MM-YYYY 的日期字符串。我需要将日,月和年作为单独的字符串获取。php 中是否有内置函数,或者我应该使用字符串操作函数并自己编写一个函数。

编辑:

我试过什么

$getdate = DateTime::createFromFormat("d-m-Y", $date);
echo $date->format("d");

错误:

Call to a member function format() on a non-object in...
<?php
    $year = date("Y", strtotime($yourDate));
    $month = date("m", strtotime($yourDate));
    $day = date("d", strtotime($yourDate));
?>

编辑

你也可以这种方法

$date = explode("-", $yourDate);
$day = $date[0];
$month = $date[1];
$year = $date[2];

这应该适合您:

(有了这个,你有日,月和年作为单独的变量)

在这里,我只是explode()字符串并用list()保存它们

$date = "15-03-2015";
list($day, $month, $year) = explode("-", $date);

你打赌!可以使用内置的 DateTime 类根据所需的格式分析日期:

$format = 'd-m-Y';
$date = DateTime::createFromFormat($format, '15-02-2009');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "'n";

资料来源:http://php.net/manual/en/datetime.createfromformat.php