dongzong8110 2015-11-24 03:11
浏览 64
已采纳

如何在PHP中将日期时间划分为单独的日期

I need to divide time period for example from:

2015-11-22 11:22:33 to 2015-11-24 02:02:04

into something like this:

2015-11-22 11:22:33 - 2015-11-22 23:59:59
2015-11-23 00:00:00 - 2015-11-23 23:59:59
2015-11-24 00:00:00 - 2015-11-24 02:02:04.

It has to work also for periods shorter than 24h, so for

2015-11-22 11:22:33 to 2015-11-23 02:02:04 

I need this:

2015-11-22 11:22:33 - 2015-11-22 23:59:59
2015-11-23 00:00:00 - 2015-11-23 02:02:04.

I found almost perfect piece of code, but it only works for periods longer than 24h and I don't know how to tune it.

<?php
$start_date = '27:04:2013';
$start_time = '16:30';
$end_date = '29:04:2013';
$end_time = '22:30';

// Date input strings and generate a suitable DatePeriod
$start = DateTime::createFromFormat("d:m:Y H:i", "$start_date $start_time");
$end = DateTime::createFromFormat("d:m:Y H:i", "$end_date $end_time");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    // Get midnight at start of current day
    $date_start = clone $date;
    $date_start->modify('midnight');

    // Get 23:59:59, end of current day
    // (moving to midnight of next day might be good too)
    $date_end = clone $date;
    $date_end->modify('23:59:59');

    // Take care of partial days
    $date_start = max($start, $date_start);
    $date_end = min($end, $date_end);

    // Here you would construct your array of
    // DateTime pairs, or DateIntervals, as you want.
    printf(
        "%s -> %s 
",
        $date_start->format('Y-m-d H:i'),
        $date_end->format('Y-m-d H:i')
    );
} 
?>

展开全部

  • 写回答

2条回答 默认 最新

  • dscpg80066 2015-11-24 03:52
    关注

    Try this:

    $date1 = '2015-11-22 11:22:33';
    $date2 = '2015-11-23 12:22:34';
    
    $f1 = strtotime($date1);
    $f2 = strtotime(substr($date1, 0, 10) . " 23:59:59");
    
    while($f2 < strtotime($date2)) {
        print(date('Y-m-d H:i:s',$f1) .' - ' .date('Y-m-d H:i:s',$f2).'<br>');
        $f1 = strtotime(date('Y-m-d H:i:s', $f2) .' +1 second');
        $f2 = strtotime(date('Y-m-d H:i:s', $f2) .' +1 day');
    }
    
    print(date('Y-m-d H:i:s',$f1) .' - ' .$date2.'<br>');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部