php - 我们如何在 php 中拆分日期?

标签 php

我们如何使用 PHP 拆分日期? PHP 中是否有任何内置函数?

2016-11-01 10:00:00 till 2016-11-03 18:00:00

我需要将以上日期拆分为所需日期:-

2016-11-01 10:00:00 till 23:59:59
2016-11-02 00:00:00 till 23:59:59
2016-11-03 00:00:00 till 18:00:00

最佳答案

据我所知,PHP 不提供此类内置功能。<​​/p>

但是您可以使用 DateTime 对象轻松实现此目的:

$interval = '2016-11-01 10:00:00 till 2016-11-03 18:00:00';
$dates = explode(' till ', $interval);

if(count($dates) == 2) {
    $current = $begin = new DateTime($dates[0]);
    $end = new DateTime($dates[1]);

    $intervals = [];

    // While more than 1 day remains
    while($current->diff($end)->format('%a') >= 1) {

        $nextDay = clone $current;
        $nextDay->setTime(23,59,59);

        $intervals []= [
            'begin' => $current->format('Y-m-d H:i:s'),
            'end'   => $nextDay->format('Y-m-d H:i:s'),
        ];
        $current = clone $nextDay;
        $current->setTime(0,0,0);
        $current->modify('+1 day');
    }

    // Last interval : from $current to $end
    $intervals []= [
        'begin' => $current->format('Y-m-d H:i:s'),
        'end'   => $end->format('Y-m-d H:i:s'),
    ];

    print_r($intervals);
}

关于php - 我们如何在 php 中拆分日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840174/

相关文章:

php - Laravel 和 Mailgun 无法正常工作

php - 如何在服务器的文件系统中正确存储图像(带有数字名称)

php - 用 $test ["index"替换 php4 样式数组 $test[index] 的正则表达式]

php - 使用 Doctrine ORM : Custom repository

php - 如何在 CURLOPT_POSTFIELDS 中包含数组数据?

php - 在 GET 请求 RESTful API 中作为查询参数的 ID 数组

php - Laravel5 中的一对多关系无法正常工作

php - “PHP Fatal error: Constant expression contains invalid operations”,何时初始化静态内联?

php - 什么是APC内部调试?

java - 如何使用没有名字的 GSON?