我需要在PHP中将时间缩短到最接近的四分之一小时。时间从日期时间列中的MySQL数据库中提取,格式为2010-03-18 10:50:00
。
示例:
我假设floor()
涉及但不确定如何处理它。
由于
答案 0 :(得分:67)
$seconds = time();
$rounded_seconds = round($seconds / (15 * 60)) * (15 * 60);
echo "Original: " . date('H:i', $seconds) . "\n";
echo "Rounded: " . date('H:i', $rounded_seconds) . "\n";
此示例获取当前时间并将其舍入到最近区域,并打印原始时间和舍入时间。
PS :如果您要围绕向下将round()
替换为floor()
。
答案 1 :(得分:29)
你的全部功能将是这样的......
function roundToQuarterHour($timestring) {
$minutes = date('i', strtotime($timestring));
return $minutes - ($minutes % 15);
}
答案 2 :(得分:11)
$now = getdate();
$minutes = $now['minutes'] - $now['minutes']%15;
//Can add this to go to the nearest 15min interval (up or down)
$rmin = $now['minutes']%15;
if ($rmin > 7){
$minutes = $now['minutes'] + (15-$rmin);
}else{
$minutes = $now['minutes'] - $rmin;
}
$rounded = $now['hours'].":".$minutes;
echo $rounded;
答案 3 :(得分:8)
要使用最接近的四分之一小时,请使用以下代码
<?php
$time = strtotime("01:08");
echo $time.'<br />';
$round = 15*60;
$rounded = round($time / $round) * $round;
echo date("H:i", $rounded);
?>
01:08成为01:15
答案 4 :(得分:5)
最近我喜欢用TDD/unit testing方式解决问题。我最近不再编程PHP了,但这就是我想出来的。说实话,我实际上看了这里的代码示例,并选择了我认为已经正确的代码示例。接下来,我想通过使用您在上面提供的测试进行单元测试来验证这一点。
require_once 'PHPUnit/Framework.php';
require_once 'Time.php';
class TimeTest extends PHPUnit_Framework_TestCase
{
protected $time;
protected function setUp() {
$this->time = new Time(10, 50);
}
public function testConstructingTime() {
$this->assertEquals("10:50", $this->time->getTime());
$this->assertEquals("10", $this->time->getHours());
$this->assertEquals("50", $this->time->getMinutes());
}
public function testCreatingTimeFromString() {
$myTime = Time::create("10:50");
$this->assertEquals("10", $myTime->getHours());
$this->assertEquals("50", $myTime->getMinutes());
}
public function testComparingTimes() {
$timeEquals = new Time(10, 50);
$this->assertTrue($this->time->equals($timeEquals));
$timeNotEquals = new Time(10, 44);
$this->assertFalse($this->time->equals($timeNotEquals));
}
public function testRoundingTimes()
{
// Round test time.
$roundedTime = $this->time->round();
$this->assertEquals("10", $roundedTime->getHours());
$this->assertEquals("45", $roundedTime->getMinutes());
// Test some more times.
$timesToTest = array(
array(new Time(1,00), new Time(1,12)),
array(new Time(3,15), new Time(3,28)),
array(new Time(1,00), new Time(1,12)),
);
foreach($timesToTest as $timeToTest) {
$this->assertTrue($timeToTest[0]->equals($timeToTest[0]->round()));
}
}
}
<?php
class Time
{
private $hours;
private $minutes;
public static function create($timestr) {
$hours = date('g', strtotime($timestr));
$minutes = date('i', strtotime($timestr));
return new Time($hours, $minutes);
}
public function __construct($hours, $minutes) {
$this->hours = $hours;
$this->minutes = $minutes;
}
public function equals(Time $time) {
return $this->hours == $time->getHours() &&
$this->minutes == $time->getMinutes();
}
public function round() {
$roundedMinutes = $this->minutes - ($this->minutes % 15);
return new Time($this->hours, $roundedMinutes);
}
public function getTime() {
return $this->hours . ":" . $this->minutes;
}
public function getHours() {
return $this->hours;
}
public function getMinutes() {
return $this->minutes;
}
}
alfred@alfred-laptop:~/htdocs/time$ phpunit TimeTest.php
PHPUnit 3.3.17 by Sebastian Bergmann.
....
Time: 0 seconds
OK (4 tests, 12 assertions)
答案 5 :(得分:5)
$minutes = ($minutes - ($minutes % 15));
答案 6 :(得分:2)
对于我的系统,我想添加计划在我的服务器上每隔5分钟运行一次的作业,我希望在下一个第5分钟的块中运行相同的作业,然后是15,30,60,120,240分钟, 1天和2天后,这个函数计算的是
function calculateJobTimes() {
$now = time();
IF($now %300) {
$lastTime = $now - ($now % 300);
}
ELSE {
$lastTime = $now;
}
$next[] = $lastTime + 300;
$next[] = $lastTime + 900;
$next[] = $lastTime + 1800;
$next[] = $lastTime + 3600;
$next[] = $lastTime + 7200;
$next[] = $lastTime + 14400;
$next[] = $lastTime + 86400;
$next[] = $lastTime + 172800;
return $next;
}
echo "The time now is ".date("Y-m-d H:i:s")."<br />
Jobs will be scheduled to run at the following times:<br /><br />
<ul>";
foreach(calculateJobTimes() as $jTime) {
echo "<li>".date("Y-m-d H:i:s", $jTime).'</li>';
}
echo '</ul>';
答案 7 :(得分:2)
这是一个老问题,但最近实施了自己,我将分享我的解决方案: -
public function roundToQuarterHour($datetime) {
$datetime = ($datetime instanceof DateTime) ? $datetime : new DateTime($datetime);
return $datetime->setTime($datetime->format('H'), ($i = $datetime->format('i')) - ($i % 15));
}
public function someQuarterHourEvent() {
print_r($this->roundToQuarterHour(new DateTime()));
print_r($this->roundToQuarterHour('2016-10-19 10:50:00'));
print_r($this->roundToQuarterHour('2016-10-19 13:12:00'));
print_r($this->roundToQuarterHour('2016-10-19 15:28:00'));
}
答案 8 :(得分:1)
我需要一种方法来完成这一天,并切断除此之外的一切:
$explodedDate = explode("T", gmdate("c",strtotime("now")));
$expireNowDate = date_create($explodedDate[0]);
strtotime为我提供了“now”的时间戳,gmdate转换为ISO格式(类似“2012-06-05T04:00:00 + 00:00”),然后我在“T”使用爆炸,在$ explosionDate的第0个索引中给出“2012-06-05”,然后将其传递给date_create以获取日期对象。
不确定是否所有这些都是必要的,但似乎比通过并减去秒,分钟,小时等要少得多。
答案 9 :(得分:1)
// time = '16:58'
// type = auto, up, down
function round_time( $time, $round_to_minutes = 5, $type = 'auto' ) {
$round = array( 'auto' => 'round', 'up' => 'ceil', 'down' => 'floor' );
$round = @$round[ $type ] ? $round[ $type ] : 'round';
$seconds = $round_to_minutes * 60;
return date( 'H:i', $round( strtotime( $time ) / $seconds ) * $seconds );
}
答案 10 :(得分:0)
使用内置的PHP函数进行舍入时间很重要,要考虑到日期和时间。例如,四舍五入到最接近的小时数时,2020-10-09 23:37:35
必须变成2020-10-10 00:00:00
。
整点到最近的时间:
$time = '2020-10-09 23:37:35';
$time = date("Y-m-d H:i:s", round(strtotime($time) / 3600) * 3600); // 2020-10-10 00:00:00
$time = '2020-10-09 23:15:35';
$time = date("Y-m-d H:i:s", round(strtotime($time) / 3600) * 3600); // 2020-10-09 23:00:00
时间倒计时到最接近的15分钟:
$time = '2020-10-09 23:15:35';
$time = date("Y-m-d H:i:s", floor(strtotime($time) / (60*15))*(60*15)); // 2020-10-09 23:15:00
$time = '2020-10-09 23:41:35';
$time = date("Y-m-d H:i:s", floor(strtotime($time) / (60*15))*(60*15)); // 2020-10-09 23:30:00
如果您需要将向上舍入到最接近的15分钟,请将floor
更改为ceil
,例如
$time = date("Y-m-d H:i:s", ceil(strtotime($time) / (60*15))*(60*15)); // 2020-10-09 23:45:00
如果您需要将时间四舍五入为分钟,您可以简单地执行以下操作:
$time = date("Y-m-d H:i:s", ceil(strtotime($time) / (60*20))*(60*20)); // 2020-10-10 00:00:00
答案 11 :(得分:0)
令我惊讶的是,没有人提到惊人的Carbon library(通常在Laravel中使用)。
/**
*
* @param \Carbon\Carbon $now
* @param int $minutesChunk
* @return \Carbon\Carbon
*/
public static function getNearestTimeRoundedDown($now, $minutesChunk = 30) {
$newMinute = $now->minute - ($now->minute % $minutesChunk);
return $now->minute($newMinute)->startOfMinute(); //https://carbon.nesbot.com/docs/
}
测试用例:
public function testGetNearestTimeRoundedDown() {
$this->assertEquals('2018-07-06 14:00:00', TT::getNearestTimeRoundedDown(Carbon::parse('2018-07-06 14:12:59'))->format(TT::MYSQL_DATETIME_FORMAT));
$this->assertEquals('14:00:00', TT::getNearestTimeRoundedDown(Carbon::parse('2018-07-06 14:29:25'))->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('14:30:00', TT::getNearestTimeRoundedDown(Carbon::parse('2018-07-06 14:30:01'))->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('18:00:00', TT::getNearestTimeRoundedDown(Carbon::parse('2019-07-06 18:05:00'))->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('18:45:00', TT::getNearestTimeRoundedDown(Carbon::parse('2019-07-06 18:50:59'), 15)->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('18:45:00', TT::getNearestTimeRoundedDown(Carbon::parse('2019-07-06 18:49:59'), 15)->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('10:15:00', TT::getNearestTimeRoundedDown(Carbon::parse('1999-12-30 10:16:58'), 15)->format(TT::HOUR_MIN_SEC_FORMAT));
$this->assertEquals('10:10:00', TT::getNearestTimeRoundedDown(Carbon::parse('1999-12-30 10:16:58'), 10)->format(TT::HOUR_MIN_SEC_FORMAT));
}
答案 12 :(得分:0)
简单的解决方案:
$oldDate = "2010-03-18 10:50:00";
$date = date("Y-m-d H:i:s", floor(strtotime($oldDate) / 15 / 60) * 15 * 60);
如果要进行整理,可以将floor
更改为ceil
。
答案 13 :(得分:0)
可以帮助别人。对于任何语言。
roundedMinutes = yourRoundFun(Minutes / interval) * interval.
E.g。间隔可以是5分钟,10分钟,15分钟,30分钟。 然后四舍五入的分钟可以重置为相应的日期。
yourDateObj.setMinutes(0)
yourDateObj.setMinutes(roundedMinutes)
答案 14 :(得分:0)
这是我目前正在使用的功能:
/**
* Rounds a timestamp
*
* @param int $input current timestamp
* @param int $round_to_minutes rounds to this minute
* @param string $type auto, ceil, floor
* @return int rounded timestamp
*/
static function roundToClosestMinute($input = 0, $round_to_minutes = 5, $type = 'auto')
{
$now = !$input ? time() : (int)$input;
$seconds = $round_to_minutes * 60;
$floored = $seconds * floor($now / $seconds);
$ceiled = $seconds * ceil($now / $seconds);
switch ($type) {
default:
$rounded = ($now - $floored < $ceiled - $now) ? $floored : $ceiled;
break;
case 'ceil':
$rounded = $ceiled;
break;
case 'floor':
$rounded = $floored;
break;
}
return $rounded ? $rounded : $input;
}
希望它可以帮助某人:)
答案 15 :(得分:0)
我编写了一个功能,可以将时间戳舍入为秒或分钟。
我可能不是最高效的方式,但我认为PHP并不关心一些简单的循环。
在您的情况下,您只需通过MySQL日期时间:
<?php echo date('d/m/Y - H:i:s', roundTime(strtotime($MysqlDateTime), 'i', 15)); ?>
返回:closests舍入值(向上和向下看!)
功能:
<?php
function roundTime($time, $entity = 'i', $value = 15){
// prevent big loops
if(strpos('is', $entity) === false){
return $time;
}
// up down counters
$loopsUp = $loopsDown = 0;
// loop up
$loop = $time;
while(date($entity, $loop) % $value != 0){
$loopsUp++;
$loop++;
}
$return = $loop;
// loop down
$loop = $time;
while(date($entity, $loop) % $value != 0){
$loopsDown++;
$loop--;
if($loopsDown > $loopsUp){
$loop = $return;
break;
}
}
$return = $loop;
// round seconds down
if($entity == 'i' && date('s', $return) != 0){
while(intval(date('s', $return)) != 0){
$return--;
}
}
return $return;
}
?>
如果您想要向上或向下舍入到秒,并将15替换为您想要上升或下降的秒数或分钟数,则可以简单地将$ entity替换为's'。
答案 16 :(得分:-2)
虽然通常最适合使用基于日期时间的函数来操纵日期时间,但此任务的要求不涉及任何与时间有关的特殊处理,这是对特定子字符串执行计算的简单任务,并且用数学结果替换子字符串。
并不是每个人都喜欢正则表达式,但是它确实提供了一种使输入字符串发生变异的单功能技术。
代码:(Demo)
$timeString = "2010-03-18 10:50:57";
// PHP7.4+ arrow syntax
echo preg_replace_callback(
'~:\K(\d{2}).*~',
fn($m) => $m[1] - $m[1] % 15 . ':00',
$timeString
);
echo "\n---\n";
// below PHP7.3
echo preg_replace_callback(
'~:\K(\d{2}).*~',
function($m) {return $m[1] - $m[1] % 15 . ':00';},
$timeString
);
输出:
2010-03-18 10:45:00
---
2010-03-18 10:45:00
注意,如果处理仅时间(用冒号分隔)字符串,则此正则表达式模式也将同样有效。 (Demo)