Pergunta

When Start date is given it should get the end date by fetching only sunday or mon, tue, wed or ,mon to fri or tue, thurs, sat using php. pls anyone help me.....


Here is my html code:




 <label>Start Date:</label><input type="text" id="txtStartDate" name="sd"></input>
 <td>days</td>
<td>
<select name="days">
    <option value="" >only sunday</option> 
    <option value="batch">sat and sun</option>
    <option value="">M-F</option>
    <option value="">M-W-F</option>
    <option value="">TU-THUR-SAT</option>
 </td>
 <td>
    <input type="submit" value="Submit" name="sub"  />
 </td>

<?php
//$startdate=$_POST['sd'];
$startdate='2013-12-25';
$date=date_create($startdate);
date_add($date,date_interval_create_from_date_string("10 days"));
echo date_format($date,"Y-m-d");
?>

it only fetches using number of days but i want to get using specific days.

Foi útil?

Solução

Store that days that you want to use in the option values ie

<select name="days">
    <option value="sunday" >only sunday</option> 
    <option value="saturday-sunday">sat and sun</option>
    <option value="monday-tuesday-wednesday-thursday-friday">Monday to Friday</option>
    <option value="monday-wednesday">Only Monday or Wednesday</option>
</select>

if (isset($_POST['sd']) && isset($_POST['days'])) {

    $startDate = new DateTime($_POST['sd']);
    $days = explode('-', $_POST['days']);
    $count = count($days);
    $dates = array();

    $currentDate = $startDate->format('Y-m-d');
    $j = 0;

    for ($i=0;$i<10;$i++) {

        $day = $days[$j];
        $a = new DateTime($currentDate);
        $a->modify("next $day");
        $dates[] = $currentDate = $a->format('Y-m-d');

        $j = (($j+1) == $count) ? 0 : $j++; 

    } 

    foreach ($dates as $date) {
        echo $date.'<br />';
    }
}

Hope this helps! :)

EDIT

or if you only want the last one of the array:

instead of the foreach use

echo end($dates);

Outras dicas

Consider using strtotime

    <option value="SUNDAY" >only sunday</option> 
    <option value="SATSUN">sat and sun</option>
    <option value="MF">M-F</option>
    <option value="MWF">M-W-F</option>
    <option value="TUTHURSAT">TU-THUR-SAT</option>


    <?php

    $option = //get selected option;
    $startDate = //get selected date;
    $days = array();
    switch($option){
        case 'SUNDAY' : $days[] = 'next sunday'; break;
        case 'SATSUN' : $days[] = 'next saturday'; $days[] = 'next sunday'; break;
        //etc
    }

    $count = 0;
    $endDate = $startDate;
    while ($count < 10){
        $index = $count++ % count($days);
        $endDate = date('Y-m-d' , strtotime($days[$index] , strtotime($endDate)));
    }

    echo $endDate;

Demo

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top