我需要在PHP中将时间缩短到最接近的四分之一小时。时间从日期时间列中的MySQL数据库中提取,格式为2010-03-18 10:50:00
。
例:
我假设floor()
参与但不知道如何去做。
谢谢
你的全部功能将是这样的......
function roundToQuarterHour($timestring) {
$minutes = date('i', strtotime($timestring));
return $minutes - ($minutes % 15);
}
// 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 );
}
我编写了一个函数来完成将时间戳舍入为秒或分钟的技巧。
我可能不是最高效的方式,但我认为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,你只需用's'替换$ entity。
这是我目前正在使用的功能:
/**
* 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;
}
希望它可以帮助别人:)
可能会帮助别人。对于任何语言。
roundedMinutes = yourRoundFun(Minutes / interval) * interval.
例如。间隔可以是5分钟,10分钟,15分钟,30分钟。然后四舍五入的分钟可以重置为相应的日期。
yourDateObj.setMinutes(0)
yourDateObj.setMinutes(roundedMinutes)
简单方案:
$oldDate = "2010-03-18 10:50:00";
$date = date("Y-m-d H:i:s", floor(strtotime($oldDate) / 15 / 60) * 15 * 60);
如果你想围捕,你可以将floor
改为ceil
。
我很惊讶没有人提到令人惊奇的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));
}
$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()
。
$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;
要使用最接近的四分之一小时,请使
<?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
$minutes = ($minutes - ($minutes % 15));
最近我喜欢解决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分钟的块中运行相同的作业,然后是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>';
这是一个老问题,但最近我自己实施了我将分享我的解决方案: -
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'));
}
我需要一种方法来结束这一天,并切断除此之外的一切:
$explodedDate = explode("T", gmdate("c",strtotime("now")));
$expireNowDate = date_create($explodedDate[0]);
strtotime给我一个“now”的时间戳,gmdate转换为ISO格式(类似“2012-06-05T04:00:00 + 00:00”),然后我在“T”使用爆炸,给我“ 2012-06-05“在$ explosionDate的第0个索引中,然后传入date_create以获取日期对象。
不确定是否所有这些都是必要的,但它似乎比通过并减去秒,分钟,小时等要少得多。