[精讚] [會員登入]
1375

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] 處理mail 函式的標題中文字亂碼 PHP的mail函式若標題有中文字得先處理過,否則收信者會看到亂碼

[PHP] 隨機產生一個顏色字串 讓PHP 隨機產生一個顏色字串

[PHP] codeignitor4+ smarty4 這篇整合 php 的framework codeignitor4 + smarty4。

[PHP>7.3] switch中的 Did you mean to use "continue 2"? 除錯 這近更新 PHP到7.3版以後,出現這樣的錯:targeting switch is equivalent to "break". Did you mean to use "continue 2"?解決方法

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

設定Google analytics API #2 -- PHP的程式安裝和撰寫 讓你的網站能夠存取你的Google analytics上面的資料

隨機好文

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

APACHE的記錄檔格式 LogFormat 語法 在APACHE中有定義一些記錄的語法模版 在 /etc/httpd/conf/httpd.conf 中: LogForm

讓radio box 或checkbox 好按 在行動裝置下,radio box及checkbox變得很難按得到

兩次使用InnoDB的慘痛經驗 Mysql 的Innodb引擎雖然好用,但是我得說說我兩次的慘痛經驗,這讓我考慮以後可能不會再使用innodb了

[SIP] OPENSER LINUX版本安裝全記錄 [SIP] OPENSER LINUX版本安裝全記錄