从php数组创建一个新日期 [英] Create a new date from php array

查看:96
本文介绍了从php数组创建一个新日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组创建日期。有什么功能可以做到这一点?我所知道的是,我可以访问字段并从中创建日期。

I'm trying to create a date from array. Is there any function that could accomplish this? What i know is i can access to fields and create date from that.

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


推荐答案

我使用了 DateTime :: createFromFormat vsprintf 从数组中构造一个时间字符串,并得出以下结果:

I used DateTime::createFromFormat and vsprintf to construct a time string from the array, and came up with this:

<?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');

输出(您可以调整格式:

Outputs (and you can tweak the format:

30/05/2017 10:48 pm

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

Actually you probably don't even need to use DateTime but I would suggest you do as you can then further manipulate it (add time intervals or change the format), you could probably just do:

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

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

这篇关于从php数组创建一个新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆