[精讚] [會員登入]
1326

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] 資料庫的使用方法整理2/2 CI3 承襲 CI2,有很多的builder class可以用,依各人的使用習慣,有人喜歡一堆sql字串,有人喜歡用helper

Smarty安裝 smarty 是著名的樣版引擎,非常的好用,用多了突然發現拿掉smarty反而不會寫php了,以下是安裝過程..

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

PHP程式經驗 #2 -- print和echo的差異 常在寫php的人一定會想知道echo和print這兩個函數有什麼不一樣 驗證 1. 比較print 和echo 函式的執

[PHP] 使用FTP PHP 上使用 FTP 的寫法

隨機好文

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

UTF-8 BOM (Byte Order Mark) 的問題 在 Michael Kaplan 那看到 Every character has a story #4: U+feff

看懂DSUB DVI HDMI USB等各式影音接頭 看懂DSUB DVI HDMI等各式影音接頭

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

維修冰箱 維修冰箱