2016-11-28 2 views
5

Как мы можем разделить даты с помощью PHP? Есть ли встроенная функция в PHP?Как мы можем разделить даты в php?

2016-11-01 10:00:00 till 2016-11-03 18:00:00 

мне нужно разделить выше даты, чтобы требуемые сроки: -

2016-11-01 10:00:00 till 23:59:59 
2016-11-02 00:00:00 till 23:59:59 
2016-11-03 00:00:00 till 18:00:00 
+1

, откуда '23: 59: 59' это происходит от? –

+0

@Anant Он исходит из календаря. –

+5

Посмотрите: http://stackoverflow.com/q/4312439/3933332 как начало – Rizier123

ответ

5

К моему PHP знаний не обеспечивает такие встроенные функции.

Но вы можете легко достигнуть этого с го DateTime объекта:

$interval = '2016-11-01 10:00:00 till 2016-11-03 18:00:00'; 
$dates = explode(' till ', $interval); 

if(count($dates) == 2) { 
    $current = $begin = new DateTime($dates[0]); 
    $end = new DateTime($dates[1]); 

    $intervals = []; 

    // While more than 1 day remains 
    while($current->diff($end)->format('%a') >= 1) { 

     $nextDay = clone $current; 
     $nextDay->setTime(23,59,59); 

     $intervals []= [ 
      'begin' => $current->format('Y-m-d H:i:s'), 
      'end' => $nextDay->format('Y-m-d H:i:s'), 
     ]; 
     $current = clone $nextDay; 
     $current->setTime(0,0,0); 
     $current->modify('+1 day'); 
    } 

    // Last interval : from $current to $end 
    $intervals []= [ 
     'begin' => $current->format('Y-m-d H:i:s'), 
     'end' => $end->format('Y-m-d H:i:s'), 
    ]; 

    print_r($intervals); 
} 
+0

Спасибо. Это отлично работает для меня. –

+0

Добро пожаловать :) – Max

3

Вы можете использовать цикл для достижения такого типа результата. Ваше требование заключается в том, чтобы печатать дату в разнице на один день между датой начала и окончания. У меня есть код для этого.

<?php 
$startDate = strtotime('2016-11-01 10:00:00'); 
$endDate = strtotime('2016-11-03 18:00:00'); 

for ($loopStart = $startDate; $loopStart <= $endDate; $loopStart = strtotime('+1 day', $loopStart)) { 

    // check last date 
    if($endDate >= strtotime('+1 day', $loopStart)){ 
     echo date('Y-m-d', $loopStart).' 23:59:59'; 
    } 
    else{ 
     echo date('Y-m-d', $loopStart).' '.date('H:i:s',$endDate); 
    } 

    echo "<br>"; 

} 

?> 

Выходной код -

2016-11-01 23:59:59 
2016-11-02 23:59:59 
2016-11-03 18:00:00 
+1

Если я добавил '$ startDate = strtotime ('2016-11-28 07:58:18'); $ endDate = strtotime ('2016-11-29 07:58:18'); 'Результат, который я получаю, -' 2016-11-28 07:58:18
2016-11-29 07:58:18
'. В этом случае это неверно. –

+0

Позвольте мне проверить и исправить. –

+0

Для этого случая нам нужно обновить инструкцию> = in if. Просто обновите условия if, как будто ($ endDate> = strtotime ('+ 1 день', $ loopStart)) { –

Смежные вопросы