将日期范围划分为相应的星期 [英] Split date ranges into corresponding weeks

查看:92
本文介绍了将日期范围划分为相应的星期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从and到的日期范围,我想把它转换成几周. 假设从日期12014年1月1日到日期2014年10月31日

I have date ranges called from and to.I want to convert it to weeks. Suppose from date is 1-10-2014 and to date is 31-10-2014

那么结果是:

第一周:2014年1月10日至2014年4月10日 2nd:2014/05/10至2014/11/10 3rd:2014/12/10至2014/10/10 4th:19-10-2014至25-10-2014 5th:26-10-2014至31-10-2014

1st week : 01-10-2014 to 04-10-2014 2nd : 05-102014 to 11-10-2014 3rd : 12-10-2014 to 18-10-2014 4th : 19-10-2014 to 25-10-2014 5th : 26-10-2014 to 31-10-2014

在php.I中尝试了一些代码,但是没有给出绝对结果,仅给出01到7、8到14等. 请帮助.

In php.I try several code but that didn't given the absolute result only give 01 to 7 , 8 to 14 etc. Pls help.

我已经尝试了以下答案

Get the date of one week from today with PHP in stack overflow


date("Y-m-d",strtotime("+1 week"));

推荐答案

此代码段将星期日作为一周的第一天:

This snippet uses Sunday as the first day of the week:

    $start = new DateTime('2014-10-01');
    $end = new DateTime('2014-10-31 23:59');
    $interval = new DateInterval('P1D');
    $dateRange = new DatePeriod($start, $interval, $end);

    $weekNumber = 1;
    $weeks = array();
    foreach ($dateRange as $date) {
        $weeks[$weekNumber][] = $date->format('Y-m-d');
        if ($date->format('w') == 6) {
            $weekNumber++;
        }
    }

每个星期都有一天.

如果只需要每周的头几天和最后几天,则可以使用array_shiftarray_pop进行获取.例如,在第一周,您可以使用:

If you just want the first and last days of each week then you can just use array_shift and array_pop to get them. For example, for the first week you can use:

    $wk1Start = array_shift($weeks[1]); //gives you first day of week 1
    $wk1End = array_pop($weeks[1]); // give you the last day of week 1

如果您需要每周的开始和结束日期,可以采用以下方法:

If you want the start and end dates for each week, here is a way of doing it:

    $ranges = array_map(function($week) {
        return 'start: ' . array_shift($week) 
            . ', end: ' . array_pop($week); },
    $weeks);

这是$ranges对我的输出:

    Array
    (
        [1] => start: 2014-10-01, end: 2014-10-04
        [2] => start: 2014-10-05, end: 2014-10-11
        [3] => start: 2014-10-12, end: 2014-10-18
        [4] => start: 2014-10-19, end: 2014-10-25
        [5] => start: 2014-10-26, end: 2014-10-31
    )

这篇关于将日期范围划分为相应的星期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆