WordPress函数:human_time_diff 几秒几分几小时前

追格官方小助手/ 2023年01月31日/ WordPress/ 浏览 910

经常见到 几秒、几分、几小时前…… 类似的时间显示方式。比如,文章发布时间,其实就是计算文章发布时间和当前时间的差值。这个计算不难,但是 WordPress 已经提供了现成的轮子,为什么不用呢?


函数原型:


human_time_diff( int $from, int $to ): string


这个函数的作用,就是计算 $from 和 $to 两个时间戳时间的差值,返回类似 1小时,5分钟,2天之类,对阅读更加友好的时间。


使用举例:


<?php
$lastmodified = get_the_modified_time('U');
$posted = get_the_time('U');
echo "Posted " . human_time_diff($posted,current_time( 'U' )). "ago";
echo "</br>";
  if ($lastmodified > $posted) {
	  echo "Edited " . human_time_diff($lastmodified,current_time('U')) . " ago";   
  } 
?>


发表评论

暂无评论,抢个沙发...

客服 工单