-1

I'm trying to generate a rough way of selecting a date in a PHP page, very primitive but it is what i was asked to produce.

basically i'm trying to produce a select drop down in HTML which will have a range of dates (in dd/mm/yyyy format)

it will include today's date (12/03/2015) and the range will be 10 days from today's date, but will need to some how follow the standard calendar (for example 31 or 30 days in month...)

can this be done? if so can someone help me out please

Stephen Jackson
  • 260
  • 2
  • 6
  • 20

1 Answers1

1

Have a look at DatePeriod. You can create a DatePeriod and map over it to create an array of dates, like so:

// create DatePeriod with the following arguments:
//
// * DateTime for current datetime
// * DateInterval of 1 day
// * Recurrences - today's date *plus* this number of repeated dates
$period = new DatePeriod(new DateTime(), new DateInterval('P1D'), 9);

// Convert DatePeriod to array of DateTime objects
// Map over array
// Build array of formatted date strings
$dates = array_map(function($dt) {
    return $dt->format('d/m/Y');
}, iterator_to_array($period));

// Done :)
var_dump($dates);

This yields something like:

array (size=11)
  0 => string '12/03/2015' (length=10)
  1 => string '13/03/2015' (length=10)
  2 => string '14/03/2015' (length=10)
  3 => string '15/03/2015' (length=10)
  4 => string '16/03/2015' (length=10)
  5 => string '17/03/2015' (length=10)
  6 => string '18/03/2015' (length=10)
  7 => string '19/03/2015' (length=10)
  8 => string '20/03/2015' (length=10)
  9 => string '21/03/2015' (length=10)

Note that recurrences is one less as it does not include the start date.

Hope this helps :)

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48