ora:获取当前日期时间
It’s common to present dates on the Web in a format such as Published on September 12th, 2015, or 09/12/2015, 09:41:23 and 2015-09-12.
通常以诸如发布于2015年9月12日或09/12 / 2015、09:41:23和2015-09-12之类的格式在Web上显示日期。
Each of these examples tells the full date and/or time of some kind of activity – be it a published article, or a reader comment, or perhaps an uploaded video.
每个示例都说明了某种活动的完整日期和/或时间-无论是发表的文章,读者的评论,还是上传的视频。
Date formats like this might seem perfectly reasonable. After all, they’re informative and human-readable! Well yes, but “human-readable” doesn’t necessary mean users will readily be able to understand how recently the activity has occurred. The Web is a fast-moving place, and giving your content a sense of freshness could be the key to engaging with your audience! So, let’s look at how we could improve on these common date formats.
这样的日期格式似乎很合理。 毕竟,它们内容丰富且易于理解! 是的,但是“人类可读”不是必需的,这意味着用户将很容易理解活动最近发生的时间。 网络是一个快速发展的地方,为您的内容提供新鲜感可能是与观众互动的关键! 因此,让我们看一下如何改进这些常见的日期格式。
一个小把戏 (A Little Trick)
Once again, let’s say you have stumbled on a post that was actually published just a couple of minutes ago, but the subheading of the post states this:
再说一次,您偶然发现了实际上是在几分钟前发布的帖子,但是该帖子的副标题指出:
Published on September 12th, 2016
发表于2016年9月12日
… or this:
… 或这个:
Published on 2016-09-12, 09:41:23
发表于2016-09-12,09:41:23
The problem with these messages is that they don’t communicate the feeling that your website has just been updated or that you do that very often. So, surely it be more inviting – and much clearer – to present the time this way:
这些消息的问题在于它们没有传达您的网站刚刚更新或您经常这样做的感觉。 因此,以这种方式呈现时间肯定会更吸引人并且更清晰:
Published 2 minutes ago
2分钟前发布
Seen this many times before? But how many of you have built this into your projects? Take Facebook for example: what would it look like if they presented the dates for the latest content as in my first example? Compare the left and right columns in the following image:
以前看过这么多次了吗? 但是你们当中有多少人已将其构建到项目中? 以Facebook为例:如果像我的第一个示例一样,他们提供最新内容的日期会怎么样? 比较下图中的左列和右列:
![timestamp formats compared](https://i-blog.csdnimg.cn/blog_migrate/1af88f3c57e936cc9f31f2a140fbbe38.gif)
The left column’s dates aren’t that attractive, are they? I’ll wager the right hand examples are more appealing to you. Knowing that the content is fresh is very important – especially on the social networks, where people are more likely to ignore content that’s old or not clearly timestamped.
左栏的日期不是很吸引人吗? 我打赌右手的例子对您更具吸引力。 知道内容是新鲜的非常重要-尤其是在社交网络上,在该社交网络上,人们更有可能会忽略过时的内容或未加盖时间戳的内容。
打印更好的日期 (Printing Better Dates)
In order to present better dates, you’ll need some server-side scripting, and I’ll use PHP for this demo. I created a tiny function called time_ago()
, as shown here:
为了提供更好的日期 ,您将需要一些服务器端脚本,并且我将在此演示中使用PHP。 我创建了一个名为time_ago()
的微型函数,如下所示:
<?php
define( TIMEBEFORE_NOW, 'now' );
define( TIMEBEFORE_MINUTE, '{num} minute ago' );
define( TIMEBEFORE_MINUTES, '{num} minutes ago' );
define( TIMEBEFORE_HOUR, '{num} hour ago' );
define( TIMEBEFORE_HOURS, '{num} hours ago' );
define( TIMEBEFORE_YESTERDAY, 'yesterday' );
define( TIMEBEFORE_FORMAT, '%e %b' );
define( TIMEBEFORE_FORMAT_YEAR, '%e %b, %Y' );
function time_ago( $time )
{
$out = ''; // what we will print out
$now = time(); // current time
$diff = $now - $time; // difference between the current and the provided dates
if( $diff < 60 ) // it happened now
return TIMEBEFORE_NOW;
elseif( $diff < 3600 ) // it happened X minutes ago
return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES );
elseif( $diff < 3600 * 24 ) // it happened X hours ago
return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS );
elseif( $diff < 3600 * 24 * 2 ) // it happened yesterday
return TIMEBEFORE_YESTERDAY;
else // falling back on a usual date format as it happened later than yesterday
return strftime( date( 'Y', $time ) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time );
}
?>
Let’s look at some details of this code.
让我们看一下这段代码的一些细节。
The only argument you must provide is
$time
, and it’s a date in Unix Timestamp – such astime_ago( 1442082961 )
.您必须提供的唯一参数是
$time
,它是Unix Timestamp中的一个日期,例如time_ago( 1442082961 )
。Examples of what the function will return in respect of the
$time
passed:有关传递的
$time
的函数返回值的示例:now – if it happened less than 60 seconds ago (
TIMEBEFORE_NOW
)现在 -如果发生的时间少于60秒前(
TIMEBEFORE_NOW
)3 minutes ago – if less than 60 minutes ago (
TIMEBEFORE_MINUTE(S)
)3分钟前–如果少于60分钟前(
TIMEBEFORE_MINUTE(S)
)8 hours ago – if less than 24 hours ago (
TIMEBEFORE_HOUR(S)
)8小时前–如果少于24小时前(
TIMEBEFORE_HOUR(S)
)yesterday – if less than 48 hours ago (
TIMEBEFORE_YESTERDAY
)昨天-如果少于48小时前(
TIMEBEFORE_YESTERDAY
)12 Sep – if more than 48 hours and happened this year (
TIMEBEFORE_FORMAT
)9月12日–如果今年发生的时间超过48小时(
TIMEBEFORE_FORMAT
)12 Sep, 2015 – if happened not this year (
TIMEBEFORE_FORMAT_YEAR
).2015年9月12日–如果不是今年(
TIMEBEFORE_FORMAT_YEAR
)。
Examples of what the function will return in respect of the
$time
passed:有关传递的
$time
的函数返回值的示例:The PHP definitions are for separating the config-like data from the function code (it would be a good practice to put all of the
define()
occurrences into a config file and the function in helpers file).PHP定义用于从函数代码中分离类似config的数据(将所有
define()
出现位置放入配置文件中并将函数放入辅助文件中是一种很好的做法)。{num}
in definitions are replaced with actual numbers (minutes or hours).定义中的
{num}
被替换为实际数字(分钟或小时)。I use
strftime()
instead ofdate()
to avoid language/locale issues.我使用
strftime()
而不是date()
来避免语言/区域设置问题 。
So, for example, if you want to get this onto your WordPress site, you’d simply write this:
因此,例如,如果您想将其添加到WordPress网站,则只需编写以下代码:
<?=time_ago( get_the_time( 'U' ) )?>
Or if it was some other hypothetical CMS:
还是其他假设的CMS:
<?=time_ago( $post->date_created )?>
Or the static way:
还是静态方式:
<?=time_ago( 1447571705 )?>
可访问性和可用性 (Accessibility & Usability)
There’s a specific HTML element that you should use for presenting dates: <time>
. In our case, when using the time_ago
function, the value of the time element is not always in a valid date format (like yesterday or 3 minutes ago). Therefore, you should also provide a fallback value by using [datetime]
attribute:
您应该使用一个特定HTML元素来显示日期: <time>
。 在我们的例子中,使用time_ago
函数时,time元素的值并不总是采用有效的日期格式(例如昨天或3分钟前 )。 因此,您还应该使用[datetime]
属性提供后备值:
Published <time
datetime="<?=date( 'Y-m-d', $time )?>"
title="<?=strftime( date( 'Y', $time ) ==
date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time )?>">
<?=time_ago( $time )?>
</time>
This would result in better accessibility, for example:
这将导致更好的可访问性,例如:
Published <time datetime="2015-09-12" title="September 12">3 minutes ago</time>
Did you spot the [title]
attribute? It’s a tiny usability improvement: putting the cursor over date text shows a message presented in the title attribute. That’s for the users who, for some reason, were looking for the “real” dates. Here’s a little CSS trick to beef up the feeling that there is something more:
您发现[title]
属性了吗? 这是一个很小的可用性改进:将光标放在日期文本上可以显示在title属性中显示的消息。 这是出于某种原因而正在寻找“真实”日期的用户的。 这是一个CSS技巧,可以增强感觉:
time[title]
{
cursor: help;
}
![CSS help cursor](https://i-blog.csdnimg.cn/blog_migrate/88048e7aaac4a361fdcd696a37a5297e.gif)
JavaScript增强 (JavaScript Enhancement)
There’s one more thing we can do! Have you noticed that Facebook also increments the dates in real time? Just watch at 3 mins for a minute and it will turn into 4 mins and so on. So, there are types of websites were this works out as a really nice enhancement. It wouldn’t be useful on an article post like this, but It’s perfect on a site like Readerrr:
我们还可以做一件事! 您是否注意到Facebook还实时增加日期? 只需观看3分钟一分钟,它就会变成4分钟 ,依此类推。 因此,有些类型的网站可以很好地增强它的功能。 在像这样的文章中它不会有用,但是在像Readerrr这样的网站上是完美的:
<time data-time="<?=$time?>" ...
Finally, we need to convert the PHP code into a JavaScript equivalent. I’ve done this for you in vanilla JS (though a jQuery version is available as well). The script walks through each time[data-time]
element once every minute (setTimeout( updateDates, 1000 * 60 )
) and updates the values:
最后,我们需要将PHP代码转换为等效JavaScript。 我已经在香草JS中为您完成了此操作(尽管也提供了jQuery版本)。 该脚本每分钟一次遍历每个time[data-time]
元素( setTimeout( updateDates, 1000 * 60 )
)并更新值:
// ...
var elements = document.querySelectorAll( 'time[data-time]' ),
updateDates = function()
{
Array.prototype.forEach.call( elements, function( entry )
{
var out = '';
// ...
entry.textContent = out;
});
setTimeout( updateDates, 1000 * 60 );
};
setTimeout( updateDates, 1000 * 60 );
// ...
![A JavaScript demo](https://i-blog.csdnimg.cn/blog_migrate/b260872d56bd8a7338e06a18543fd333.gif)
在线演示和代码下载 (Online Demo and Code Download)
You can check out an online demo of the above code or download the full demo code.
还有一件事 (One more thing)
In the examples above, the full date is presented if the activity has occurred three or more days ago. But it’s quite easy to extend the script for presenting the time in the ways like 5 days ago, 2 weeks ago and 1 month ago, and so on:
在上面的示例中,如果活动在三天或更早之前发生,则会显示完整日期。 但是,以5天前 , 2周前和1个月前等方式扩展用于显示时间的脚本非常容易:
// ...
define( TIMEBEFORE_DAYS, '{num} days ago' );
define( TIMEBEFORE_WEEK, '{num} week ago' );
define( TIMEBEFORE_WEEKS, '{num} weeks ago' );
define( TIMEBEFORE_MONTH, '{num} month ago' );
define( TIMEBEFORE_MONTHS, '{num} months ago' );
function time_before( $time )
{
// ...
elseif( $diff < 3600 * 24 * 7 )
return str_replace( '{num}', round( $diff / ( 3600 * 24 ) ), TIMEBEFORE_DAYS );
elseif( $diff < 3600 * 24 * 7 * 4 )
return str_replace( '{num}', ( $out = round( $diff / ( 3600 * 24 * 7 ) ) ), $out == 1 ? TIMEBEFORE_WEEK : TIMEBEFORE_WEEKS );
elseif( $diff < 3600 * 24 * 7 * 4 * 12 )
return str_replace( '{num}', ( $out = round( $diff / ( 3600 * 24 * 7 * 4 ) ) ), $out == 1 ? TIMEBEFORE_MONTH : TIMEBEFORE_MONTHS );
else
// ...
}
结语 (Wrap Up)
User experience and satisfaction is in details. Sometimes a simple detail – such as a dynamic date format – is enough to make our websites a little bit better.
用户体验和满意度非常详细。 有时,一个简单的细节(例如动态日期格式)足以使我们的网站更好一点。
So, what do you think of this solution? Would you consider using it on your next project? Do you have any questions about it? Please let me know in the comments.
那么,您如何看待该解决方案? 您会考虑在下一个项目中使用它吗? 您对此有任何疑问吗? 请在评论中让我知道。
By the way, I hope somebody can tell Instagram people that 122w isn’t cool, and that 2.4yrs would be much easier to understand. That would be better, wouldn’t it?
顺便说一句,我希望有人能告诉Instagram人们122w并不酷,而2.4yrs会更容易理解。 那会更好,不是吗?
翻译自: https://www.sitepoint.com/counting-the-ago-time-how-to-keep-publish-dates-fresh/
ora:获取当前日期时间