[精讚] [會員登入]
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程式經驗 #2 -- print和echo的差異 常在寫php的人一定會想知道echo和print這兩個函數有什麼不一樣 驗證 1. 比較print 和echo 函式的執

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

作業上傳程式 提供學生作業上傳的程式

[CodeIgniter 3] 取得controller和method的方法 CodeIgniter 3 取得controller和method的方法

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

利用 php 木馬作為駭客攻擊的手法 利用 php 木馬作為駭客攻擊的手法

隨機好文

[jQuery] select 元件的取值及給值 html中的元件select,在jquery中要如何使用?

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法

維修冰箱 維修冰箱

NETCRAFT發現你的網站及作業系統 NETCRAFT可以發現你的網站及作業系統

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