RoiEX RoiEX - 1 month ago 20
Javascript Question

Calculate Time since MySQL timestamp

Disclaimer: My JavaScript skills are very limited, and so is my knowledge of the JavaScript standard functions/library. Forgive me, if my question is stupid.

I basically have a standard MySQL timestamp given and I want the user to see, how much time has passed since this timestamp.

I know that there is a time_diff function, but that's too generic for me, I need a user-readable solution. Preferably something like "Written 34 seconds ago", "written 2 hours ago", "written a week ago", "written a year ago", "written on 24th December 2005", etc.
If there is an already built-in function (or a popular library), please let me know...

This alone would be enough, but I'd like to hear your suggestions on how to write a timer updating this every time unit (The first minute it should update every second, the first hour every minute etc.).


Another solution I found was using the MySQL timestampdiff method, still too generic, but I wouldn't have to worry about possible Time-Zone differences. (Client in EST, server elsewhere).

Updating could be done via ajax requests (probably bad idea when using multiple timestamps) or via manually incrementing the given time.


TL;DR
What I need:
A function formatting a time difference to a user/easy readable format.

Any help is appreciated!

Answer

You can easily convert a Unix timestamp value into javascript date object by

var date = new Date(unix_timestamp*1000);

Then you can make use of this plugin

http://timeago.yarp.com/

For your need for a count down timer I suggest you to use

http://countdownjs.org/