[精讚] [會員登入]
1339

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

你可能感興趣的文章

[Smarty5] 如何在樣版中使用php本身的函式 解決 smarty5版後不能直接叫用 php函式的問題

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

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

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

[PHP] 移除檔案的UTF8 BOM 移除檔案的UTF8 BOM

[PHP] 解析二進位圖片 使用php來解析png圖片,把資料寫在16進位格式

隨機好文

使用Google尋找你的手機 這近發現google竟然可以用來找android的手機,而且不需要經過什麼設定或安裝軟體。

HP SAS硬碟leds燈號說明 HP SAS硬碟leds燈號(hp g7/g6系統適用)說明

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

如何在linux下執行java 原生的java應用程式可以使用簡單的方法在console下面寫出來,適合作簡單的應用

安裝SPHINX支援中文 新版本的 sphinx 和舊版不同,網路上很多範例和教學是不能用的。此文是安裝和設定方法分享