search
HomeTechnology peripheralsIt IndustryTime Ago: How to Display Publish Dates as Time Since Posted

Time Ago: How to Display Publish Dates as Time Since Posted

Key Takeaways

  • Displaying publish dates as time since posted, such as “Published 2 minutes ago”, can increase the sense of freshness and engagement with your audience, as opposed to traditional date formats like “Published on September 12th, 2016”.
  • A PHP function called time_ago() can be used to convert Unix Timestamp into a human-readable format such as “now”, “3 minutes ago”, “8 hours ago”, “yesterday”, or specific dates if the activity occurred more than two days ago.
  • The HTML
  • JavaScript can be used to increment the dates in real time, similar to Facebook. This can be a nice enhancement for certain types of websites where real-time updates are important.

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.

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

… or this:

Published on 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

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:

Time Ago: How to Display Publish Dates as Time Since Posted

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:

<span><span><?php </span></span><span>
</span><span>    <span>define( TIMEBEFORE_NOW,         'now' );
</span></span><span>    <span>define( TIMEBEFORE_MINUTE,      '{num} minute ago' );
</span></span><span>    <span>define( TIMEBEFORE_MINUTES,     '{num} minutes ago' );
</span></span><span>    <span>define( TIMEBEFORE_HOUR,        '{num} hour ago' );
</span></span><span>    <span>define( TIMEBEFORE_HOURS,       '{num} hours ago' );
</span></span><span>    <span>define( TIMEBEFORE_YESTERDAY,   'yesterday' );
</span></span><span>    <span>define( TIMEBEFORE_FORMAT,      '%e %b' );
</span></span><span>    <span>define( TIMEBEFORE_FORMAT_YEAR, '%e %b, %Y' );
</span></span><span>
</span><span>    <span>function time_ago( $time )
</span></span><span>    <span>{
</span></span><span>        <span>$out    = ''; // what we will print out
</span></span><span>        <span>$now    = time(); // current time
</span></span><span>        <span>$diff   = $now - $time; // difference between the current and the provided dates
</span></span><span>
</span><span>        <span>if( $diff </span><span>            <span>return TIMEBEFORE_NOW;
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES );
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS );
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return TIMEBEFORE_YESTERDAY;
</span></span><span>
</span><span>        <span>else // falling back on a usual date format as it happened later than yesterday
</span></span><span>            <span>return strftime( date( 'Y', $time ) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time );
</span></span><span>    <span>}
</span></span><span>
</span><span><span>?></span></span></span></span></span></span></span>

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 as time_ago( 1442082961 ).
  • Examples of what the function will return in respect of the $time passed:
    • now – if it happened less than 60 seconds ago (TIMEBEFORE_NOW)
    • 3 minutes ago – if less than 60 minutes ago (TIMEBEFORE_MINUTE(S))
    • 8 hours ago – if less than 24 hours ago (TIMEBEFORE_HOUR(S))
    • yesterday – if less than 48 hours ago (TIMEBEFORE_YESTERDAY)
    • 12 Sep – if more than 48 hours and happened this year (TIMEBEFORE_FORMAT)
    • 12 Sep, 2015 – if happened not this year (TIMEBEFORE_FORMAT_YEAR).
  • 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).
  • {num} in definitions are replaced with actual numbers (minutes or hours).
  • I use strftime() instead of date() to avoid language/locale issues.

So, for example, if you want to get this onto your WordPress site, you’d simply write this:

<span><span>=time_ago( get_the_time( 'U' ) )?></span></span>

Or if it was some other hypothetical 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:

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:

<span>time<span><span>[title]</span></span>
</span><span>{
</span>    <span>cursor: help;
</span><span>}</span>

Time Ago: How to Display Publish Dates as Time Since Posted

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:

<span><span><?php </span></span><span>
</span><span>    <span>define( TIMEBEFORE_NOW,         'now' );
</span></span><span>    <span>define( TIMEBEFORE_MINUTE,      '{num} minute ago' );
</span></span><span>    <span>define( TIMEBEFORE_MINUTES,     '{num} minutes ago' );
</span></span><span>    <span>define( TIMEBEFORE_HOUR,        '{num} hour ago' );
</span></span><span>    <span>define( TIMEBEFORE_HOURS,       '{num} hours ago' );
</span></span><span>    <span>define( TIMEBEFORE_YESTERDAY,   'yesterday' );
</span></span><span>    <span>define( TIMEBEFORE_FORMAT,      '%e %b' );
</span></span><span>    <span>define( TIMEBEFORE_FORMAT_YEAR, '%e %b, %Y' );
</span></span><span>
</span><span>    <span>function time_ago( $time )
</span></span><span>    <span>{
</span></span><span>        <span>$out    = ''; // what we will print out
</span></span><span>        <span>$now    = time(); // current time
</span></span><span>        <span>$diff   = $now - $time; // difference between the current and the provided dates
</span></span><span>
</span><span>        <span>if( $diff </span><span>            <span>return TIMEBEFORE_NOW;
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES );
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS );
</span></span><span>
</span><span>        <span>elseif( $diff </span><span>            <span>return TIMEBEFORE_YESTERDAY;
</span></span><span>
</span><span>        <span>else // falling back on a usual date format as it happened later than yesterday
</span></span><span>            <span>return strftime( date( 'Y', $time ) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time );
</span></span><span>    <span>}
</span></span><span>
</span><span><span>?></span></span></span></span></span></span></span>

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:

<span><span>=time_ago( get_the_time( 'U' ) )?></span></span>

Time Ago: How to Display Publish Dates as Time Since Posted

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:

=time_ago( $post->date_created )?>

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?

Frequently Asked Questions (FAQs) about Counting the ‘Ago’ Time

How does the ‘ago’ time function work in JavaScript?

The ‘ago’ time function in JavaScript is a way to display the time elapsed since a particular event occurred. It uses the Date object to calculate the difference between the current time and the time of the event. This difference is then converted into seconds, minutes, hours, days, weeks, or years, depending on the magnitude of the difference. The result is a string that represents the elapsed time in a human-readable format, such as “5 minutes ago” or “2 days ago”.

How can I implement the ‘ago’ time function in my web application?

To implement the ‘ago’ time function in your web application, you need to create a JavaScript function that takes a Date object as input and returns a string representing the elapsed time. This function should calculate the difference between the current time and the input date, convert this difference into the appropriate units, and format the result as a string. You can then call this function whenever you need to display the ‘ago’ time.

What are the benefits of using the ‘ago’ time function?

The ‘ago’ time function provides a more intuitive and user-friendly way to display time information. Instead of showing the exact date and time of an event, which can be difficult to interpret and compare, the ‘ago’ time function shows the elapsed time in a format that is easy to understand and relate to. This can enhance the user experience and make your web application more engaging and interactive.

Can the ‘ago’ time function handle future dates?

Yes, the ‘ago’ time function can handle future dates. If the input date is later than the current date, the function will calculate the time until the event instead of the time since the event. The result will be a string that represents the remaining time in a human-readable format, such as “in 5 minutes” or “in 2 days”.

How can I customize the ‘ago’ time function to suit my needs?

The ‘ago’ time function is highly customizable. You can modify the function to use different units of time, different formats for the output string, or different rules for rounding the elapsed time. You can also add support for different languages or locales, if needed. By tweaking the function, you can make it fit perfectly with the design and functionality of your web application.

Is the ‘ago’ time function compatible with all browsers?

The ‘ago’ time function is based on standard JavaScript features, so it should be compatible with all modern web browsers. However, it’s always a good idea to test your code on different browsers and platforms to ensure that it works correctly and consistently.

Can the ‘ago’ time function handle time zones?

Yes, the ‘ago’ time function can handle time zones. The function uses the Date object, which automatically takes into account the time zone of the user’s device. This means that the ‘ago’ time will be accurate regardless of the user’s location or time zone.

How can I debug the ‘ago’ time function if it’s not working correctly?

If the ‘ago’ time function is not working correctly, you can use the console.log() method to print out the input date, the current date, and the calculated difference. This will help you identify any errors or inconsistencies in the function. You can also use the debugger tool in your browser’s developer tools to step through the function and inspect its behavior in detail.

Can I use the ‘ago’ time function in a mobile app?

Yes, you can use the ‘ago’ time function in a mobile app. JavaScript is a versatile language that can be used in many different environments, including mobile apps. The function should work the same way in a mobile app as it does in a web application.

How can I optimize the performance of the ‘ago’ time function?

To optimize the performance of the ‘ago’ time function, you can use techniques such as memoization or caching. These techniques can reduce the number of calculations that the function needs to perform, making it faster and more efficient. You can also minimize the number of times the function is called by updating the ‘ago’ time only when necessary, rather than on every page load or every second.

The above is the detailed content of Time Ago: How to Display Publish Dates as Time Since Posted. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Behind the first Android access to DeepSeek: Seeing the power of womenBehind the first Android access to DeepSeek: Seeing the power of womenMar 12, 2025 pm 12:27 PM

The rise of Chinese women's tech power in the field of AI: The story behind Honor's collaboration with DeepSeek women's contribution to the field of technology is becoming increasingly significant. Data from the Ministry of Science and Technology of China shows that the number of female science and technology workers is huge and shows unique social value sensitivity in the development of AI algorithms. This article will focus on Honor mobile phones and explore the strength of the female team behind it being the first to connect to the DeepSeek big model, showing how they can promote technological progress and reshape the value coordinate system of technological development. On February 8, 2024, Honor officially launched the DeepSeek-R1 full-blood version big model, becoming the first manufacturer in the Android camp to connect to DeepSeek, arousing enthusiastic response from users. Behind this success, female team members are making product decisions, technical breakthroughs and users

DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!Mar 12, 2025 pm 12:21 PM

DeepSeek released a technical article on Zhihu, introducing its DeepSeek-V3/R1 inference system in detail, and disclosed key financial data for the first time, which attracted industry attention. The article shows that the system's daily cost profit margin is as high as 545%, setting a new high in global AI big model profit. DeepSeek's low-cost strategy gives it an advantage in market competition. The cost of its model training is only 1%-5% of similar products, and the cost of V3 model training is only US$5.576 million, far lower than that of its competitors. Meanwhile, R1's API pricing is only 1/7 to 1/2 of OpenAIo3-mini. These data prove the commercial feasibility of the DeepSeek technology route and also establish the efficient profitability of AI models.

Top 10 Best Free Backlink Checker Tools in 2025Top 10 Best Free Backlink Checker Tools in 2025Mar 21, 2025 am 08:28 AM

Website construction is just the first step: the importance of SEO and backlinks Building a website is just the first step to converting it into a valuable marketing asset. You need to do SEO optimization to improve the visibility of your website in search engines and attract potential customers. Backlinks are the key to improving your website rankings, and it shows Google and other search engines the authority and credibility of your website. Not all backlinks are beneficial: Identify and avoid harmful links Not all backlinks are beneficial. Harmful links can harm your ranking. Excellent free backlink checking tool monitors the source of links to your website and reminds you of harmful links. In addition, you can also analyze your competitors’ link strategies and learn from them. Free backlink checking tool: Your SEO intelligence officer

Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Mar 12, 2025 pm 12:18 PM

Midea will soon release its first air conditioner equipped with a DeepSeek big model - Midea fresh and clean air machine T6. The press conference is scheduled to be held at 1:30 pm on March 1. This air conditioner is equipped with an advanced air intelligent driving system, which can intelligently adjust parameters such as temperature, humidity and wind speed according to the environment. More importantly, it integrates the DeepSeek big model and supports more than 400,000 AI voice commands. Midea's move has caused heated discussions in the industry, and is particularly concerned about the significance of combining white goods and large models. Unlike the simple temperature settings of traditional air conditioners, Midea fresh and clean air machine T6 can understand more complex and vague instructions and intelligently adjust humidity according to the home environment, significantly improving the user experience.

Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Mar 12, 2025 pm 01:48 PM

DeepSeek-R1 empowers Baidu Library and Netdisk: The perfect integration of deep thinking and action has quickly integrated into many platforms in just one month. With its bold strategic layout, Baidu integrates DeepSeek as a third-party model partner and integrates it into its ecosystem, which marks a major progress in its "big model search" ecological strategy. Baidu Search and Wenxin Intelligent Intelligent Platform are the first to connect to the deep search functions of DeepSeek and Wenxin big models, providing users with a free AI search experience. At the same time, the classic slogan of "You will know when you go to Baidu", and the new version of Baidu APP also integrates the capabilities of Wenxin's big model and DeepSeek, launching "AI search" and "wide network information refinement"

Prompt Engineering for Web DevelopmentPrompt Engineering for Web DevelopmentMar 09, 2025 am 08:27 AM

AI Prompt Engineering for Code Generation: A Developer's Guide The landscape of code development is poised for a significant shift. Mastering Large Language Models (LLMs) and prompt engineering will be crucial for developers in the coming years. Th

Building a Network Vulnerability Scanner with GoBuilding a Network Vulnerability Scanner with GoApr 01, 2025 am 08:27 AM

This Go-based network vulnerability scanner efficiently identifies potential security weaknesses. It leverages Go's concurrency features for speed and includes service detection and vulnerability matching. Let's explore its capabilities and ethical

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)