Jump to content

change yyyy-mm-dd date ranges to mm/dd/yyyy from array?


rich_traff

Recommended Posts

I have sets of date ranges stored as yyyy-mm-dd

 

example;

start date: 2011-05-26

end date: 2011-05-28

 

i have these stored in an array of arrays, print_r gives this;

Array ( [0] => Array ( [0] => 2011-05-26 [1] => 2011-05-28 ) [1] => Array ( [0] => 2011-05-28 [1] => 2011-05-30 ) [2] => Array ( [0] => 2011-06-13 [1] => 2011-06-24 ) )

 

I need to rearrange the date format to mm/dd/yyyy whilst keeping the order of the array intact. Note changing the '-' to an '/' is important.

 

I then need to be able to echo the date ranges separated by a comma, so the above array becomes

 

05/26/2011-05/28/2011, 05/28/2011-05/30/2011, 06/13/2011-06/24/2011

 

can anyone help with this?

Just a quick code that gets the job done. It's tested, but you can take a look for any possible optimisation.

 

<?php
/*
** Date Conversion
*/
$dates = array(array('2011-05-26', '2011-05-28'), array('2011-05-28', '2011-05-30'));

function convertDate (&$array, $key) {
foreach ($array as &$v) {
	list($year, $month, $day) = explode('-', $v);
	$v = $month . '/' . $day . '/' . $year;
}
}

array_walk($dates, 'convertDate');
//print_r($dates);

/*
** Dates Printing
*/
$dates_print = '';

foreach ($dates as $array) {
$values = array_values($array);
$dates_print .= implode('-', $values) . ', ';
}

$dates_print = trim($dates_print, ', ');
//echo $dates_print;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.