Turning a date into a time interval


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

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.


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.