remluben / nice-time
一个简单的类,用于以Facebook风格创建时间段的格式化输出
Requires
- php: >=5.3.0
This package is auto-updated.
Last update: 2024-09-27 00:28:24 UTC
README
#NiceTime
一个简单的类,用于以Facebook风格创建时间段的格式化输出。
它基于php.net PHP手册中php time()函数的一个简单函数: https://php.ac.cn/manual/en/function.time.php#89415
##安装
项目可通过Composer从https://packagist.org.cn获取。
将以下行添加到您的composer.json文件中
{ "require" : { "remluben/nice-time" : "dev-master" } }
##示例
以下是一个列表,列出了\Remluben\DateFormat\NiceTime类的对象在未进行任何定制的情况下可能生成的可能输出
- 1分钟前
- 从现在起3分钟
- 5天前
- 从现在起1天
- 6个月前
- 1年前
- 20年前
##定制
创建\Remluben\DateFormat\NiceTime对象实例后,修改所有标签以适应您的定制需求是至关重要的
$nt = new \Remluben\DateFormat\NiceTime();
###错误的日期标签
以下示例显示了错误的日期标签的getter方法,并使用其setter方法将其设置为空字符串。
// the default \Remluben\DateFormat\NiceTime bad date label is 'Bad date' $nt->getBadDateLabel(); $nt->setBadDateLabel('');
每次我们调用对象的format()方法并传递无效的日期字符串时,它将返回空字符串。
###没有日期标签
以下示例显示了没有日期标签的getter方法,并使用其setter方法将其设置为空字符串。
// the default NiceDate bad date label is 'No date provided' $nt->getNoDateLabel(); $nt->setNoDateLabel('');
每次我们调用对象的format()方法并传递空日期字符串时,它将返回空字符串而不是默认标签“未提供日期”。
###将来时态
将来时态字符串用于格式化未来的日期时间,并期望包含%s标志,其中时间值将被解析为。
默认值是“%s从现在开始”,这在英语中似乎是相当合适的。然而,对于某些语言,这个字符串的格式可能与英文版本有很大的不同。
// the default NiceDate future tense is '%s from now' $nt->getFutureTense(); $nt->setFutureTense('in %s');
###过去时态
默认值是“%s之前”。
有关更多信息,请参阅将来时态
###时间段
与时间段相比,我们可能遇到了定制中最困难的部分。
默认时间段如下
- 秒/秒
- 分钟/分钟
- 小时/小时
- 周/周
- 月/月
- 年/年
- 十年/十年
注意,/符号用作单数/复数单词的分隔符。这是非常重要的,因为我们希望得到格式如“1天前”,但也需要“2天前”。
示例
$nt->setPeriods(array( 'second/s', 'minute/s', 'hour/s', 'week', // oh no we made a mistake here 'month/s', 'year/s', 'decade/s', )); $date = date('Y-m-d', time() - 60 * 60 * 24 * 14); // two weeks ago // bad formatting as we missed the slash when configuring the periods above $nt->format($date); // => 2 week ago
##方法链
如上节定制中所述,存在许多方法可以自定义\Remluben\DateFormat\NiceTime对象的行为。
方法链允许您以优雅、简洁的方式进行操作
$nicetime = new \Remluben\DateFormat\NiceTime(); // some funny customizing here - use method chaining $nicetime->setBadDateLabel('wtf') ->setNoDateLabel('lol this is no date') ->setFutureTense('%s from now - what else?') ->setPastTense('%s ago... puh'); // now some output // 2 hours ago... puh echo $nicetime->format(date('Y-m-d H:i:s', time() - (2 * 60 * 60))); // 1 day from now - what else? echo $nicetime->format(date('Y-m-d H:i:s', time() + (24 * 60 * 60)));