0

I have seen some webpages(for example facebook) where created/posted date for posts are counting. For example posted now, 5 min ago, yesterday at 14 and so on.

Im working on a reactJS webpage right now where this functionality would be really nice. I am sending models to the client but these are only used to generate the react code then its not used any more.

So the question is, what would be the best way to solve this? Should I maybe create a special react datetime component that are used? And if so, how could it look like?

Edit : sorry for not being clear. The time can be calculated on server but I need it to count down live on the client.

Brigand
  • 84,529
  • 20
  • 165
  • 173
Banshee
  • 15,376
  • 38
  • 128
  • 219
  • 1
    I have always used http://momentjs.com/ It is pretty great. Does front end and server side. – Max Baldwin Feb 25 '15 at 17:39
  • It's not clear what you need help with still. It seems like you're asking for someone to code a solution? Don't you just need to send the total time up ... subtract from current time to get elapsed, and then display it using whatever means/framework you want? – WiredPrairie Feb 25 '15 at 21:34

3 Answers3

0

Have a look at moment.js, specifically "Display Time from now"

moment([2007, 0, 29]).fromNow(); // 4 years ago

http://momentjs.com/docs/#/displaying/fromnow/

mles
  • 4,534
  • 10
  • 54
  • 94
0

As I mentioned in my comment, I have always used Moment JS. Again, it does Front End and server side. This functionality is probably what you can use:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Max Baldwin
  • 3,404
  • 3
  • 26
  • 40
  • Sorry for not being clear, I can calculate this at the server manually, no problem but what I seek is a live update at the client, so when it has gone 5 min it will show posted 5 min ago and so on without reloading page. – Banshee Feb 25 '15 at 17:45
0

You need to periodically trigger a re-render so whichever components are generating the time since display will update.

Doing this with a setInterval at the top level isn't ideal, but is the easiest way to do it.

Another easy way is to create a component which takes a prop for the time to be compares against and forces itself to re-render every so often to update the displayed time.

Another way would be to keep a static list of callbacks from mounted time-displaying components which force the component to re-render and loop through them and call them periodically.

Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150