Relative Time from Timestamp


/ Published in: ActionScript 3
Save to your folder(s)

Whilst building an AS3 twitter widget i developed this code to change the timestamp formatted like this: Sun Oct 24 20:07:33 +0000 2010 to something much more usable such as '43 minutes ago' or 'about 4 days ago'


Copy this code and paste it in your HTML
  1. //###############################
  2. //Usage:
  3. var myRelativeTime:String = timestampToRelative("Sun Oct 24 20:07:33 +0000 2010");
  4. //returns a string
  5. //###############################
  6.  
  7. function timestampToRelative(timestamp:String):String {
  8. //--Parse the timestamp as a Date object--\\
  9. var pastDate:Date = new Date(timestamp);
  10. //--Get the current data in the same format--\\
  11. var currentDate:Date = new Date();
  12. //--seconds inbetween the current date and the past date--\\
  13. var secondDiff:Number = (currentDate.getTime() - pastDate.getTime())/1000;
  14.  
  15. //--Return the relative equavalent time--\\
  16. switch (true) {
  17. case secondDiff < 60 :
  18. return int(secondDiff) + ' seconds ago';
  19. break;
  20. case secondDiff < 120 :
  21. return 'About a minute ago';
  22. break;
  23. case secondDiff < 3600 :
  24. return int(secondDiff / 60) + ' minutes ago';
  25. break;
  26. case secondDiff < 7200 :
  27. return 'About an hour ago';
  28. break;
  29. case secondDiff < 86400 :
  30. return 'About ' + int(secondDiff / 3600) + ' hours ago';
  31. break;
  32. case secondDiff < 172800 :
  33. return 'Yesterday';
  34. break;
  35. default :
  36. return int(secondDiff / 86400) + ' days ago';
  37. break;
  38. }
  39. }

URL: http://bit.ly/as3twitter

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.