[精讚] [會員登入]
1243

PHP 產生連續的日期

要用PHP產生連續的日期,連續月份

分享此文連結 //n.sfs.tw/13031

分享連結 PHP 產生連續的日期@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-22 06:21:55 最後編修
2019-01-16 01:09:57 By 張○○
 

自動目錄

要產生連續日期,例如

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個月

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週日期

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

 

 

END

你可能感興趣的文章

[PHP] CodeIgniter 3+pure+smarty安裝及環境設置2/2 PHP framework CodeIgniter 3+ pure CSS +smarty Template Engine的整合#2

[phpmyadmin] 缺少 mcrypt 外掛,請檢查 PHP 設定 缺少 mcrypt 外掛,請檢查 PHP 設定,安裝php-mcrypt。

[phpmyadmin] 錯誤:您應升級到 MySQL 5.5.0 或更新版本 使用phpmyadmin4出現錯誤:您應升級到 MySQL 5.5.0 或更新版本的解決方式

使用Yahoo OAuth2 2/2 使用Yahoo OAuth2認證我的網頁

[PHP] 讀取作業系統程式執行結果 PHP讀取作業系統程式執行結果

[CodeIgniter 3] 資料庫的使用方法整理2/2 CI3 承襲 CI2,有很多的builder class可以用,依各人的使用習慣,有人喜歡一堆sql字串,有人喜歡用helper

隨機好文

[HP DL380G7] 生效啟動第3,4片網卡/開啟或關閉內建的網卡 HP DL380G7 預設第3,4片網卡裝完系統後找不到,難道是壞了?要怎麼辦?

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

魔球中小女孩唱的歌 The show 魔球中小女孩唱的歌 The show

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔

海棉寶寶超泡杯演奏的sweet victory 章魚哥和海棉寶寶在超泡杯的演奏歌曲