답변 5개 / 댓글 5개
채택된 답변
+20 포인트
Copy
$year = '2024';
$month = '03';
do {
echo $year.$month.'<br>';
$month++;
if($month < 10) $month = '0'.$month;
if($month == 13) {
$year++;
$month = '01';
}
} while($year.$month <= date('Ym'));
저 방식대로 라면..만약 2025년01월일때...
for($i=202403; $i < date("Ym"); $i++ )
이 되면..
for($i=202403; $i < 202501; $i++ )
이 되어..
202403, 202404, 202405, 202406, 202407, 202408, 202409, 202410, 202411, 202412, 202413, 202414....
202499, 202501
형식으로 표현 될겁니다.
년도의 기준을 따로 설정하시고 월로만 체크 하시는게 나으실것 같네요.
for($d=03; $d < date("m"); $d++ )
echo date("Y").$d; 형식으로
Copy
<?php
// echo date('Y-m-d'); // 2024-05-28
function get_month_range($now, $gap = '') {
$ts = strtotime($now);
if ($ts === false) {
$ts = $now;
}
if (empty($gap) == true) {
$gap = '+0';
}
$finish_v = (int)date('Ym', $ts);
$start_v = (int)date('Ym', strtotime($gap . ' month', $ts));
$start = min($start_v, $finish_v);
$finish = max($start_v, $finish_v);
$dateset = [$start];
while (current($dateset) < $finish) {
$el = date('Ym', strtotime(current($dateset) . '01 +1 month'));
$dateset[] = $el;
next($dateset);
}
return $dateset;
}
/*
// 202405
$dateset = get_month_range(time());
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
// 202403
// 202404
// 202405
$dateset = get_month_range(time(), '-2');
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
// 202405
// 202406
// 202407
$dateset = get_month_range(time(), '+2');
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
// 202309
// 202310
// 202311
// 202312
// 202401
// 202402
$dateset = get_month_range('20240213', '-5');
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
// 202403
// 202404
// 202405
// 202406
// 202407
// 202408
// 202409
// 202410
// 202411
// 202412
// 202501
// 202502
// 202503
// 202504
$diff_obj = date_diff(date_create('20240301'), date_create('20250401'));
$diff_month = 12 * $diff_obj->y + $diff_obj->m;
$dateset = get_month_range('20240301', '+' . $diff_month);
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
*/
// 202403
// 202404
// 202405
$diff_obj = date_diff(date_create('20240301'), date_create());
$diff_month = 12 * $diff_obj->y + $diff_obj->m;
$dateset = get_month_range('20240301', '+' . $diff_month);
foreach ($dateset as $v) {
echo $v . PHP_EOL;
}
Copy
for ($i = 202403; $i <= date('Ym'); $i++) {
echo $i;
}
답변을 작성하려면 로그인이 필요합니다.
심플하면서 깔끔한 코드네요.
역시 이런 로직이 들어가야하는군요..