Using JavaScript to get a users local time and difference and display as time ago

We are going to use Timeago, a jQuery plugin to display the users time with a fuzzy timestamp. For example, "about 1 day ago". You can download it here: http://timeago.yarp.com  

First we create our time HTML element:

<time class="timeago" datetime=""></time>

To get the timestamp calculation of a user, use the following for the timezone difference between UTC and Local Time and getTime to return the number of milliseconds since 1970-01-01 from the instance of the Date class.

<script>

var x = new Date();
var stamp = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;

// You could then store this timestamp in a database or something and select it later for use to display the time ago like below.

// For demo purposes, I am going to next set the time element with a datetime attribute to hold our timestamp as ISO 8601 UTC

$("time.timeago").attr("datetime":stamp); 

// Lastly we update the time element with our fuzzy time.

$("time.timeago").timeago();

</script> 

And there you have it. Of course, you would only use this for time stamping a post, join date, or something ago for it to be logical.


Comments

Popular posts from this blog

Build 6 is here

An example of chaining jQuery Ajax request callbacks

Creating hashtag hyperlinks on the fly for your website