How to create Human Friendly time format in PHP

in #utopian-io8 years ago (edited)

I am going to be explaining how you can format dates in php in a human friendly format.

This kind of formatting is mostly used by blogs and social networks to make time and dates more readable for their users.

STEP 1: Get Current time

We need to call the php function that gives the current time (time()) and then assign it to a variable ($currentTime)

$currentTime = time();

The time() will return a UNIX timestamp that will look like this (1515608889). A UNIX timestamp is just the the total number of seconds between January 1st, 1970 and the present time. It is a way to keep track of time in php.

STEP 2: Deduct time difference

We need to deduct the time of activity we are tracking from the present time. Assuming a post was made 2 days ago, the recorded time of posting will be assigned to a variable $postTime and then deducted from the current time which we got in step 1

$timestamp is the recorded date of posting which is usually gotten from a database

$timestamp should also be in seconds, it can easily gotten by recording the UNIX timestamp at the moment of post into the database

$diff = $currentTime - $timestamp;

STEP 3:Create an array of time-like words that will be used.

This depends on the language you want. in this case, english is being used. Then we assign the array to a variable called $timePhrase

$timePhrase = array('second','minute','hour','day','week','month','year','decade');

STEP 4: Create another array for time limits.

This will include timelimits for a minute, a day, a week, a month up to a year in seconds. This will be used to know when to switch the formatting language when outputting the time. For instance, to distinguish when to output a day ago or a month ago. then, we assign it to variable called $timeLimit

$timeLimit = array(1,60,3600,86400,604800,2630880,31570560,315705600);

STEP 5: Create a for() loop to manipulate the $timeLimit and the $difference in order to get the final formatted time

for($i =sizeof($timeLimit)-1; ($i >=0)&&(($no =  $diff/$length[$i])<=1); $i--); 
if($i < 0) $i=0; $_time = $currentTime  -($diff%$timeLimit[$i]);
$no = floor($no);
 if($no <> 1) 
$timePhrase[$i] .='s';
 $value=sprintf("%d %s ",$no,$timePhrase[$i]);

What the for() loop does is that it creates a condition that checks if the time difference is not negative, if it's nagative, it turns the time difference 0.

Then, it creates the formatted time by converting decimals that was gotten during the division to whole numbers using floor(), then we pluralise the $timePhrase contents in case each of the phrases needs to be more than one e.g. 2 minutes instead of 1 minute. After this, we do the final formatting using sprintf() so as to treat the number of time as an integer and the $timePhrase as a string. After that ,we echo the $value which is the formatted time.

All of the this codes can be rewritten into a function as stated below . The function receives a recorded time of activity , preferably a UNIX time stamp that can be gotten by using the php function time()

Function humantime($timestamp){
$currentTime = time();
        $diff = $currentTime - $timestamp;
        $timePhrase = array('second','minute','hour','day','week','month','year','decade');
        $timeLimit = array(1,60,3600,86400,604800,2630880,31570560,315705600);
        for($i =sizeof($timeLimit)-1; ($i >=0)&&(($no =  $diff/$timeLimit[$i])<=1); $i--); if($i < 0) $i=0; $_time = $currentTime  -($diff%$timeLimit[$i]);
        $no = floor($no); if($no <> 1) $timePhrase[$i] .='s'; $value=sprintf("%d %s ",$no,$timePhrase[$i]);
        return $value.' ago ';
}

So the above function can simply be used to return a human friendly time of when a page was last reloaded as shown below

session_start();
if (!empty($_SESSION['lastLoad'])){
    $timestamp = $_SESSION['lastLoad'];
    Function humantime($timestamp){
$currentTime = time();
        $diff = $currentTime - $timestamp;
        $timePhrase = array('second','minute','hour','day','week','month','year','decade');
        $timeLimit = array(1,60,3600,86400,604800,2630880,31570560,315705600);
        for($i =sizeof($timeLimit)-1; ($i >=0)&&(($no =  $diff/$timeLimit[$i])<=1); $i--); if($i < 0) $i=0; $_time = $currentTime  -($diff%$timeLimit[$i]);
        $no = floor($no); if($no <> 1) $timePhrase[$i] .='s'; $value=sprintf("%d %s ",$no,$timePhrase[$i]);
        return $value.' ago ';
}
echo humantime($_SESSION['lastLoad']);
}
else {echo 'reload again';}
$_SESSION['lastLoad'] = time();

You can copy this code into a php script and play around with it, you'll love it. Below is a gif animation showing me running with script in a browser and waiting each time to elongate the reload time.

lop.gif

Feel free to comment and ask any question.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

  • Suggestion: Don't forget to add extra Github link of the project to end of the post.

You can contact us on Discord.
[utopian-moderator]

thanks, Noted

So, if i understood properly, you just show me how to create the timer I see every time the sites tell me "Please do not spam" ?

Yes. Exactly! Exactly. The site records your last activity and check it against your recent activity . If it the time duration is too small, then you are considered a spammer

That s nice. I often asked myself how it works but I never been so curious to search it. Lucky to find you :) Nice job and thanks :)

You are welcome. I used to tell people that everybody needs a little knowledge of programming just so they could have basic understanding of how gadgets and software works. I am happy you appreciate this knowledge.

Im a first year student at Computer Science, but yet I havent learned about PHP and others. Just in my spare time I read about HTML, CSS and things about websites. For the moment Im working to create my first application. Hopefully, Ill hope in the future I`ll have enough time to gain knowledge as yours.

Hey @akintunde I am @utopian-io. I have just upvoted you!

Achievements

  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x