Guest User

Untitled

a guest
Aug 20th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. How to list dates in yyyy_mm format with PHP using a loop?
  2. 2011_10
  3. 2011_09
  4. 2011_08
  5. 2011_07
  6. 2011_06
  7. ...
  8. 2010_03
  9. 2009_02
  10. 2009_01
  11. 2009_12
  12. 2009_11
  13.  
  14. // Set timezone
  15. date_default_timezone_set('UTC');
  16.  
  17. // Start date
  18. $date = date('Y').'-'.date('m').'-01';
  19. // End date
  20. $end_date = '2009-1-1';
  21.  
  22. while (strtotime($date) >= strtotime($end_date))
  23. {
  24. $date = date ("Y-m-d", strtotime("-1 month", strtotime($date)));
  25. echo substr($date,0,7);
  26. echo "n";
  27. }
  28.  
  29. <?php
  30. // Set timezone
  31. date_default_timezone_set('UTC');
  32.  
  33. // Start date
  34. $date = '2009-12-06';
  35. // End date
  36. $end_date = '2020-12-31';
  37.  
  38. while (strtotime($date) <= strtotime($end_date)) {
  39. echo "$daten";
  40. $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
  41. }
  42.  
  43. ?>
  44.  
  45. $startmonth = date("m");
  46. $endmonth = 7;
  47. $startyear = date("Y");
  48. $endyear = 2012;
  49.  
  50. //First for loop to loop threw years
  51. for($i=$startyear; $i<=$endyear; $i++, $startmonth=0) {
  52. //Second for loop to loop threw months
  53. for($o=$startmonth; $o<=12; $o++) {
  54. //If statement to check and throw stop when at limits
  55. if($i == $endyear && $o <= $endmonth)
  56. echo $i."_".$o."<br/>";
  57. else
  58. break;
  59. }
  60. }
  61.  
  62. Will output:
  63. 2012_0
  64. 2012_1
  65. 2012_2
  66. 2012_3
  67. 2012_4
  68. 2012_5
  69. 2012_6
  70. 2012_7
  71.  
  72. $start = new DateTime('first day of this month');
  73. $end = new DateTime('2009-11-01');
  74. $interval = new DateInterval('P1M');
  75. $period = new DatePeriod($start, $interval, $end);
  76.  
  77. foreach ($period as $date) {
  78. echo $date->format('Y_m') . PHP_EOL;
  79. }
Add Comment
Please, Sign In to add comment