我使用DatePeriod来准备两个日期的日期,但没有工作

时间:2017-11-23 06:03:51

标签: php

我们如何在php中准备两个日期之间的日期?

我搜索过并找到了一个使用DatePeriod的方法。我尝试过这种方法,但结果却变得不同了。

DatePeriod Object
(
    [start] => DateTime Object
        (
            [date] => 2017-11-23 02:09:17.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [current] => 
    [end] => DateTime Object
        (
            [date] => 2017-11-23 05:09:17.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [interval] => DateInterval Object
        (
            [y] => 0
            [m] => 0
            [d] => 1
            [h] => 0
            [i] => 0
            [s] => 0
            [weekday] => 0
            [weekday_behavior] => 0
            [first_last_day_of] => 0
            [invert] => 0
            [days] => 
            [special_type] => 0
            [special_amount] => 0
            [have_weekday_relative] => 0
            [have_special_relative] => 0
        )

    [recurrences] => 1
    [include_start_date] => 1
)

日期从jquery帖子传递。

<?php
$dates       = '02.09.17 - 05.09.17';
$daterange   = explode(" - ", $dates);
$dateBegin   = $daterange[0];
$dateEnd     = $daterange[1];

$period      = new DatePeriod(new DateTime($daterange[0]), new DateInterval('P1D'), new DateTime($daterange[1]));                

print_r($period);

?>

1 个答案:

答案 0 :(得分:0)

创建DateTime对象时需要指定格式。正如您所看到的,它将日期字符串放在时间部分中。做这样的事情:

$date = DateTime::createFromFormat('d.m.y', '02.09.17');

或更具体地说:

$from = DateTime::createFromFormat('d.m.y', $daterange[0]);
$to = DateTime::createFromFormat('d.m.y', $daterange[1]);
$period = new DatePeriod($from, new DateInterval('P1D'), $to); 

顺便说一下,我不确定您的格式是&n;&#39; 还是&#39; mdy&#39; ,所以适当调整。