自動目錄
要產生連續日期,例如
2018-12-28
2018-12-29
2018-12-30
2018-12-31
2019-01-01
2019-01-02
或是連續的月份
2018-11
2018-12
2019-01
2019-02
2019-03
不能用數字迴圈,這樣會產生不存在的日期,因為每個月份的天數都不一樣。
簡單的作法,用 strtotime 函數。
產生目前月份的前6個月
1 2 3 4 5 6 | date_default_timezone_set( 'Asia/Taipei' ); for ( $n = 5; $n >=0; $n --){ print $ym = date ( "Y-m" , strtotime ( " -$n month" )); print "\n" ; } |
執行結果
2018-09
2018-10
2018-11
2018-12
2019-01
2019-02
最後一筆是目前的月份
產生今天的前後2週日期
1 2 3 4 5 | date_default_timezone_set( 'Asia/Taipei' ); for ( $n =7 ; $n >=-7; $n --){ print $ym = date ( "Y-m-j" , strtotime ( " -$n day" )); print "\n" ; } |
執行結果
2019-02-7
2019-02-8
2019-02-9
2019-02-10
2019-02-11
2019-02-12
2019-02-13
2019-02-14
2019-02-15
2019-02-16
2019-02-17
2019-02-18
2019-02-19
2019-02-20
2019-02-21
第3行換成 "Y-m-d" 顯示日會補0:
2019-02-08