我的日期数组如下所示:
Array(
[0] => 08/03/2017
[1] => 09/03/2017
[2] => 10/03/2017
[3] => 11/03/2017
[4] => 12/03/2017
)
Array(
[0] => 08/03/2017
[1] => 09/03/2017
[2] => 10/03/2017
[3] => 11/03/2017
[4] => 12/03/2017
[5] => 01/03/2018
)
Array(
[0] => 10/04/2017
[1] => 11/04/2017
[2] => 12/04/2017
[3] => 01/04/2018
)
我需要将这些数组的每个日期转换为m/Y
格式。
我需要将m/d/Y
格式转换为m/Y
格式,我还需要将其与m/Y
格式的当前日期进行比较。
while($row=mysql_fetch_array($result)){
$result_array[] = ($row['start_date']);
$result_array1[] = $row['start_date'];
}
有没有办法将日期数组$result_array[ ]
的格式更改为m/Y
?
Array(
[0] => 08/2017
[1] => 09/2017
[2] => 10/2017
[3] => 11/2017
[4] => 12/2017
)
Array(
[0] => 08/2017
[1] => 09/2017
[2] => 10/2017
[3] => 11/2017
[4] => 12/2017
[5] => 01/2018
)
Array(
[0] => 10/2017
[1] => 11/2017
[2] => 12/2017
[3] => 01/2018
)
答案 0 :(得分:0)
有几种方法可以使用php来处理这个问题,但我的建议是在查询的SELECT部分准备日期。
代码:(Demo)
$array1=['08/03/2017','09/03/2017','10/03/2017','11/03/2017','12/03/2017'];
$array2=['08/03/2017','09/03/2017','10/03/2017','11/03/2017','12/03/2017','01/03/2018'];
$array3=['10/04/2017','11/04/2017','12/04/2017','01/04/2018'];
//string function technique:
foreach($array1 as $date){
$result1[]=substr_replace($date,'',3,3); // replace {dd/} with an empty string
}
var_export($result1);
echo "\n\n";
// date function technique
foreach($array2 as $date){
$result2[]=date('m/Y',strtotime($date));
}
var_export($result2);
// mysql function technique *this is the best/cleanest way
$query="SELECT DATE_FORMAT(`date_fieldname`,'%m/%Y') FROM `your_tablename`"; // now prepared in resultset
echo "\n\n";
// make comparisons
$current_mo_year=date('m/Y');
foreach($array3 as $date){
$date=substr_replace($date,'',3,3); // prepare however you like
echo "Comparison between $current_mo_year & $date: ",($date==$current_mo_year?'same':'different'),"\n";
}
输出:
array (
0 => '08/2017',
1 => '09/2017',
2 => '10/2017',
3 => '11/2017',
4 => '12/2017',
)
array (
0 => '08/2017',
1 => '09/2017',
2 => '10/2017',
3 => '11/2017',
4 => '12/2017',
5 => '01/2018',
)
Comparison between 11/2017 & 10/2017: different
Comparison between 11/2017 & 11/2017: same
Comparison between 11/2017 & 12/2017: different
Comparison between 11/2017 & 01/2018: different