PHP实现上一周,上N周,上个月,上个季度

本文目的

今天实现了题目中描述的关于上XX时间的函数,这几个函数大量的使用了php日期时间相关的函数,尤其是date,所以记录于此,作为备忘录,也希望对其他同学有用。

 

上代码

<?php
/**
 * 上XXX时间函数,用于计算上一周,上n周,上个月,上个季度的时间点。
 *
 * @author bourneli(李伯韬)
 * @date 2012-12-18
 */

/**
 * 获取上个季度的开始和结束日期
 * @param int $ts 时间戳
 * @return array 第一个元素为开始日期,第二个元素为结束日期
 */
function lastQuarter($ts) {
    $ts = intval($ts);

    $threeMonthAgo = mktime(0, 0, 0, date('n', $ts) - 3, 1, date('Y', $ts));
    $year = date('Y', $threeMonthAgo);
    $month = date('n', $threeMonthAgo);
    $startMonth = intval(($month - 1)/3)*3 + 1; // 上季度开始月份
    $endMonth = $startMonth + 2; // 上季度结束月份
    return array(
        date('Y-m-1', strtotime($year . "-{$startMonth}-1")),
        date('Y-m-t', strtotime($year . "-{$endMonth}-1"))
    );
}

/**
 * 获取上个月的开始和结束
 * @param int $ts 时间戳
 * @return array 第一个元素为开始日期,第二个元素为结束日期
 */
function lastMonth($ts) {
    $ts = intval($ts);

    $oneMonthAgo = mktime(0, 0, 0, date('n', $ts) - 1, 1, date('Y', $ts));
    $year = date('Y', $oneMonthAgo);
    $month = date('n', $oneMonthAgo);
    return array(
        date('Y-m-1', strtotime($year . "-{$month}-1")),
        date('Y-m-t', strtotime($year . "-{$month}-1"))
    );
}

/**
 * 获取上n周的开始和结束,每周从周一开始,周日结束日期
 * @param int $ts 时间戳
 * @param int $n 你懂的(前多少周)
 * @param string $format 默认为'%Y-%m-%d',比如"2012-12-18"
 * @return array 第一个元素为开始日期,第二个元素为结束日期
 */
function lastNWeek($ts, $n, $format = '%Y-%m-%d') {
    $ts = intval($ts);
    $n  = abs(intval($n));

    // 周一到周日分别为1-7
    $dayOfWeek = date('w', $ts);
    if (0 == $dayOfWeek)
    {
        $dayOfWeek = 7;
    }

    $lastNMonday = 7 * $n + $dayOfWeek - 1;
    $lastNSunday = 7 * ($n - 1) + $dayOfWeek;
    return array(
        strftime($format, strtotime("-{$lastNMonday} day", $ts)),
        strftime($format, strtotime("-{$lastNSunday} day", $ts))
    );
}

//---------------------demo---------------------
$now = strftime('%Y-%m-%d', time());
echo "Today: {$now}\n";

list($start, $end) = lastNWeek(time(), 1);
echo "Last 1 week:  {$start} ~ {$end}\n";

list($start, $end) = lastNWeek(time(), 2);
echo "Last 2 week:  {$start} ~ {$end}\n";

list($start, $end) = lastNWeek(time(), 3);
echo "Last 3 week:  {$start} ~ {$end}\n";

list($start, $end) = lastMonth(time());
echo "Last month:   {$start} ~ {$end}\n";

list($start, $end) = lastQuarter(time());
echo "Last quarter: {$start} ~ {$end}\n";

?>

(前N个月,只需要稍作修改,就可以实现,这里就留给读者了。)

执行结果如下:

image

 

参考资料

posted @ 2012-12-18 18:19  bourneli  阅读(4226)  评论(0编辑  收藏  举报