动态日期数组

时间:2011-03-22 00:26:17

标签: php arrays date

我的php不是很热。

我想知道你是否可以帮助我,我正在尝试创建一个包含过去31个日期的数组。 e.g。

$dates = array("2011-03-22", "2011-03-21", "2011-03-20", "2011-03-19", ........... "2011-02-22");

赞赏的任何指示:)

感谢

alsweet

3 个答案:

答案 0 :(得分:3)

使用DateTime对象,它相当直接。 (从PHP 5.2开始提供)。

$dates = array();
$date = new DateTime();
for($i = 0; $i < 31; $i++) {
    $dates[] = $date->format('Y-m-d');
    $date->modify('-1 day');
}

答案 1 :(得分:2)

使用DateInterval

foreach(new DatePeriod(new DateTime("30 days ago"), new DateInterval('P1D'), 30) as $d) 
 $a[] = $d->format('Y-m-d');

$a = array_reverse($a); // assuming you want today to be index 0

答案 2 :(得分:1)

这是使用unix时间戳,mktime()date()的老派方法。

<?php

// mktime() gives you a unix timestamp, with the
// current timestamp returned if you don't supply
// an argument.
$now = mktime();
$dates = array();

for ($i = 1; $i < 31; $i++) {
    // date() allows you to format a unix timestamp.
    // Take now (mktime()), and iteratively substract
    // 60 seconds x 60 minutes x 24 hours (gives you 
    // one day in seconds), and multiply that by the 
    // days-in-seconds offset, or $i, and run that
    // date() to produce the timestamp that date you
    // will use to produce the plaintext formatted date.
    $dates[$i-1] = date('Y-m-d',$now-($i*(60*60*24)));
}

?>

如果你:

echo '<pre>';
print_r($dates);

您将获得以下内容:

Array
(
    [0] => 2011-03-20
    [1] => 2011-03-19
    [2] => 2011-03-18
    [3] => 2011-03-17
    [4] => 2011-03-16
    [5] => 2011-03-15
    [6] => 2011-03-14
    [7] => 2011-03-13
    [8] => 2011-03-12
    [9] => 2011-03-11
    [10] => 2011-03-10
    [11] => 2011-03-09
    [12] => 2011-03-08
    [13] => 2011-03-07
    [14] => 2011-03-06
    [15] => 2011-03-05
    [16] => 2011-03-04
    [17] => 2011-03-03
    [18] => 2011-03-02
    [19] => 2011-03-01
    [20] => 2011-02-28
    [21] => 2011-02-27
    [22] => 2011-02-26
    [23] => 2011-02-25
    [24] => 2011-02-24
    [25] => 2011-02-23
    [26] => 2011-02-22
    [27] => 2011-02-21
    [28] => 2011-02-20
    [29] => 2011-02-19
)

http://php.net/manual/en/function.date.php

http://www.php.net/manual/en/function.mktime.php

相关问题