Posted By

sidneydekoning on 06/05/09


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

zeman
roark
bazjapan


Turning a date into a time interval


 / Published in: ActionScript 3
 

URL: http://weblogs.macromedia.com/cantrell/archives/2009/06/actionscript_fu.html

ActionScript function for turning a date into a time interval

While working on a small Twitter utility, I wrote a function to turn a date into a time interval string. For instance, rather than formatting the date, it returns strings like "Just posted," "6 minutes ago," "4 hours ago," or "20 days ago". It's not a complex function, but I thought I'd post it here in case it might save someone a few minutes of coding. The less time we spend writing code someone else has already written, the more time we can spend innovating.

  1. private function formatDate(d:Date):String
  2. {
  3. var now:Date = new Date();
  4. var diff:Number = (now.time - d.time) / 1000; // convert to seconds
  5. if (diff < 60) // just posted
  6. {
  7. return "Just posted";
  8. }
  9. else if (diff < 3600) // n minutes ago
  10. {
  11. return (Math.round(diff / 60) + " minutes ago");
  12. }
  13. else if (diff < 86400) // n hours ago
  14. {
  15. return (Math.round(diff / 3600) + " hours ago");
  16. }
  17. else // n days ago
  18. {
  19. return (Math.round(diff / 86400) + " days ago");
  20. }
  21. }

Report this snippet  

You need to login to post a comment.