从php数组创建一个新日期

时间:2017-04-18 15:09:45

标签: php date datetime

我正在尝试从数组创建日期。有没有可以实现这一目标的功能?我所知道的是我可以访问字段并从中创建日期。

'endDate' => array(
        'month' => '05',
        'day' => '30',
        'year' => '2017',
        'hour' => '10',
        'min' => '48',
        'meridian' => 'pm'
    )

3 个答案:

答案 0 :(得分:2)

我使用DateTime::createFromFormatvsprintf从数组中构造一个时间字符串,并提出了这个:

<?php
$endDate = array(
    'month' => '05',
    'day' => '30',
    'year' => '2017',
    'hour' => '10',
    'min' => '48',
    'meridian' => 'pm'
);

$date = DateTime::createFromFormat('d/m/Y h:i a', vsprintf('%s/%s/%s %s:%s %s', [
    $endDate['day'],
    $endDate['month'],
    $endDate['year'],
    $endDate['hour'],
    $endDate['min'],
    $endDate['meridian'],
]));

echo $date->format('d/m/Y h:i a');

输出(您可以调整格式:

30/05/2017 10:48 pm

实际上你可能甚至不需要使用DateTime,但我建议你这样做,然后你可以进一步操作它(添加时间间隔或更改格式),你可能只是这样做:< / p>

printf('%s/%s/%s %s:%s %s', [
    $endDate['day'],
    $endDate['month'],
    $endDate['year'],
    $endDate['hour'],
    $endDate['min'],
    $endDate['meridian'],
]

演示:https://eval.in/778600

答案 1 :(得分:0)

您可以将值汇总到值日期字符串中,然后创建DateTime来电strtotime的新实例。

$endtime = [
    'month' => '05',
    'day' => '30',
    'year' => '2017',
    'hour' => '10',
    'min' => '48',
    'meridian' => 'pm'
];
$datetime = DateTime::createFromFormat("Y-m-d h:i A", "{$endtime['year']}-{$endtime['month']}-{$endtime['day']} {$endtime['hour']}:{$endtime['min']} {$endtime['meridian']}");
$time = strtotime("{$endtime['year']}-{$endtime['month']}-{$endtime['day']} {$endtime['hour']}:{$endtime['min']} {$endtime['meridian']}");

答案 2 :(得分:0)

没有API功能,可以实现这一目标。您可以实现自己的方法,其中应如下所示:

/**
 * Convert given array to DateTimeObject
 * @param $dateArr array containing 'day', 'month', 'year', 'hour', 'min', 'meridian'
 * @return DateTime object
 *
 * 'day' and 'month' must always be 2 numbers
 * 'year' must always be 4 numbers
 * 'hour' must always be 2 numbers (01-12)
 * 'min' must always be 2 numbers (00-59)
 * 'meridian' must always be 2 letters ('am' or 'pm')
 */
function createEndDate($dateArr) {
    return DateTime::createFromFormat('dmYhia',
        $dateArr['day'] . 
        $dateArr['month'] . 
        $dateArr['year'] .
        $dateArr['hour'] .
        $dateArr['min'] .
        strtolower($dateArr['meridian']));
}

代码示例:

$yourArr => array(
    'month' => '05',
    'day' => '30',
    'year' => '2017',
    'hour' => '10',
    'min' => '48',
    'meridian' => 'pm'
)

$endDate = createEndDate($yourArr);
// see http://php.net/manual/de/class.datetime.php for docs
echo $endDate->format('u');