How to compare post time interval since it was published ?

Asked

Viewed 300 times

1

Good staff,

I have a table where I create the posts in which each and added the date it was published, now I need to create a system for the post to appear how long it was published like facebook I would like your help to know how best to do that and how I can do it ?

1 answer

1

You have to work with timestamp.

I save the dates in the bank using:

date('Y-m-d H:i:s')

Which is the default for mysql timestamp/datatime.

Now that you have a saved pattern, while reading this you convert the date (which comes as string) to the date format with

strtotime

getting:

strtotime($suadatadobanco);

Then you will use again from the date() function to pick up the date fields you want, if you just want to use’d' day, example:

date('d', strtotime($suadatadobanco))

The return will be the day of the month of that date.

For more information about the date function visit: http://php.net/manual/en/function.date.php

Now you know how to take the dates and their elements, now it remains to calculate the date difference.

To do this you turn the dates into timestamp and then do the operations, remembering that the timestamp converts the full date into seconds, ie you sum, subtract, divide and multiply the dates using seconds, after doing so then you take the result and convert back to date.

Example:

You want to fit the difference of data_1 in relation to data_2, then you will do so:

$diferenca_em_timestamp = strtotime($suadatadobanco_data_1) - strtotime($suadatadobanco_data_2);

$difenca_em_dia = date('d', strtotime($diferenca_em_timestamp));

You can create a script like "if the date is above 7 days, display 'more than a week'" or "if it is less than 60min display 'just a few minutes'"... this goes from your logic and what you need...

But there are javascript plugins that take the date you give and make this "conversion" to days/min/months...

See the plugin:

https://github.com/phstc/jquery-dateFormat

  • Thanks for your suggestion but I had already solved practically this way I ended up converting to strtotime and do the checks through switch but thanks for your reply as soon as possible I will put the code as an answer in case someone else needs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.