gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:49:14 25 4
gpt4 key购买 nike

我们如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com