【发布时间】:2016-12-22 10:56:57
【问题描述】:
我知道碳的工作原理,但我想创建自定义碳功能。 carbon 有一个名为diffForHumans() 的函数,我想对该函数进行一些修改并调用该函数diffForHumansCustom()。如果我编辑Carbon.php 供应商文件,我可以实现我的目标,但修改将在composer update 之后消失。任何建议或代码帮助表示赞赏。
原函数
public function diffForHumans(Carbon $other = null, $absolute = false)
{
$isNow = $other === null;
if ($isNow) {
$other = static::now($this->tz);
}
$diffInterval = $this->diff($other);
switch (true) {
case ($diffInterval->y > 0):
$unit = 'year';
$delta = $diffInterval->y;
break;
case ($diffInterval->m > 0):
$unit = 'month';
$delta = $diffInterval->m;
break;
case ($diffInterval->d > 0):
$unit = 'day';
$delta = $diffInterval->d;
if ($delta >= self::DAYS_PER_WEEK) {
$unit = 'week';
$delta = floor($delta / self::DAYS_PER_WEEK);
}
break;
case ($diffInterval->h > 0):
$unit = 'hour';
$delta = $diffInterval->h;
break;
case ($diffInterval->i > 0):
$unit = 'minute';
$delta = $diffInterval->i;
break;
default:
$delta = $diffInterval->s;
$unit = 'second';
break;
}
if ($delta == 0) {
$delta = 1;
}
$txt = $delta . ' ' . $unit;
$txt .= $delta == 1 ? '' : 's';
if ($absolute) {
return $txt;
}
$isFuture = $diffInterval->invert === 1;
if ($isNow) {
if ($isFuture) {
return $txt . ' from now';
}
return $txt . ' ago';
}
if ($isFuture) {
return $txt . ' after';
}
return $txt . ' before';
}
我修改后的函数
public function diffForHumansCustom(Carbon $other = null, $absolute = false)
{
$isNow = $other === null;
if ($isNow) {
$other = static::now($this->tz);
}
$diffInterval = $this->diff($other);
switch (true) {
case ($diffInterval->y > 0):
$unit = 'year';
$delta = $diffInterval->y;
break;
case ($diffInterval->m > 0):
$unit = 'month';
$delta = $diffInterval->m;
break;
case ($diffInterval->d > 0):
$unit = 'day';
$delta = $diffInterval->d;
if ($delta >= self::DAYS_PER_WEEK) {
$unit = 'week';
$delta = floor($delta / self::DAYS_PER_WEEK);
}
break;
case ($diffInterval->h > 0):
$unit = 'hour';
$delta = $diffInterval->h;
break;
case ($diffInterval->i > 0):
$unit = 'minute';
$delta = $diffInterval->i;
break;
default:
$delta = $diffInterval->s;
$unit = 'second';
break;
}
if ($delta == 0) {
$delta = 1;
}
$txt = $delta . ' ' . $unit;
$txt .= $delta == 1 ? '' : 's';
if($unit == 'second' && $delta<=59) {
return 'Just now';
}
// Greater than 3 days
// [xx] [Month] [year, only displays if not current year'] at [time in 24 clock].
if(($unit == 'day' && $delta > 3) || ($unit == 'week') || ($unit == 'month') || ($unit == 'year')) {
$timestamp = $this->getTimestamp();
$curYear = date('Y');
$y = ($curYear == date('Y', $timestamp)) ? '': date('Y', $timestamp);
$date = date('j F '.$y, $timestamp);
$time = date('H:i', $timestamp);
$txt = rtrim($date).' at '.$time;
return $txt;
}
if ($absolute) {
return $txt;
}
$isFuture = $diffInterval->invert === 1;
if ($isNow) {
if ($isFuture) {
return $txt . ' from now';
}
return $txt . ' ago';
}
if ($isFuture) {
return $txt . ' after';
}
return $txt . ' before';
}
【问题讨论】:
-
创建您自己的扩展
Carbon的类(例如MyCarbon)并在您的类版本中实现该方法
标签: php laravel date datetime php-carbon