简体   繁体   中英

Calculate days in between given start date and end date in php

I have $start_date & $end_date.

I need to find out number of days with name's of days.

I tried following code snipet :

$start_date = '20-07-2012';
$end_date = '22-07-2012';
$start = strtotime($start_date);
$end = strtotime($end_date);
$interval = 2;
$out='';
$int = 24*60*60*$interval;
for($i= $start;$i<= $end; $i += $int ){

    echo date('d-m-Y',$i).'<br />';
}

output :

28-11-2014
30-11-2014

But my expected out is like :

28-11-2014 => friday
30-11-2014 => saturday

let me know what should be php code to yeild the expected output.

Day name is in 'l' (lowercase L).

If you need just string, use:

echo date('d-m-Y => l', $i) . '<br />';

If you want an array, use:

$days = array();

for ($i = $start;$i <= $end; $i += $int) {
    $days[] = array(
        'date' => date('d-m-Y', $i),
        'day'  => date('l', $i)
    );
}

print_r($days);

More info about date in the Manual

   // $array[desc:day count starting w 1][desc: 'date' or 'day'];
   // $array[2]['day'];
<?php
$start = '27-11-2014';
$end = '1-12-2014';
    function date_difference($start, $end)
    {
        $first_date = strtotime($start);
        $second_date = strtotime($end);
        $offset = $second_date-$first_date; 
        $result = array();
        for($i = 0; $i <= floor($offset/24/60/60); $i++) {
            $result[1+$i]['date'] = date('d-m-Y', strtotime($start. ' + '.$i.'  days'));
            $result[1+$i]['day'] = date('l', strtotime($start. ' + '.$i.' days'));
        }
        echo '<pre>';
        print_r($result);
        echo '</pre>';
    }
    date_difference($start, $end);
?>

result

Array
(
    [1] => Array
        (
            [date] => 27-11-2014
            [day] => Thursday
        )

    [2] => Array
        (
            [date] => 28-11-2014
            [day] => Friday
        )

    [3] => Array
        (
            [date] => 29-11-2014
            [day] => Saturday
        )

    [4] => Array
        (
            [date] => 30-11-2014
            [day] => Sunday
        )

    [5] => Array
        (
            [date] => 01-12-2014
            [day] => Monday
        )

)

try this modified code

    <?php

    $start_date = '20-07-2012';
    $end_date = '22-07-2012';
    $start = strtotime($start_date);
    $end = strtotime($end_date);
    $interval = 2;
    $out='';
    $int = 24*60*60*$interval;
    for($i= $start;$i<= $end; $i += $int ){

        echo date('d-m-Y => l',$i).'<br />';
    }
?>

output :

20-07-2012 => Friday
22-07-2012 => Sunday

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM