/ Published in: JavaScript
This takes a very readable date, such as "Fri, 4 Dec 2008 15:13:00 +0000", and outputs it as a relative date (such as "1 hour ago").
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var d = Date.parse("Fri, 4 Dec 2008 15:13:00 +0000"); var dateFunc = new Date(); var timeSince = dateFunc.getTime() - d; var inSeconds = timeSince / 1000; var inMinutes = timeSince / 1000 / 60; var inHours = timeSince / 1000 / 60 / 60; var inDays = timeSince / 1000 / 60 / 60 / 24; var inYears = timeSince / 1000 / 60 / 60 / 24 / 365; // in seconds if(Math.round(inSeconds) == 1){ document.write("1 second ago"); } else if(inMinutes < 1.01){ document.write(Math.round(inSeconds) + " seconds ago"); } // in minutes else if(Math.round(inMinutes) == 1){ document.write("1 minute ago"); } else if(inHours < 1.01){ document.write(Math.round(inMinutes) + " minutes ago"); } // in hours else if(Math.round(inHours) == 1){ document.write("1 hour ago"); } else if(inDays < 1.01){ document.write(Math.round(inHours) + " hours ago"); } // in days else if(Math.round(inDays) == 1){ document.write("1 day ago"); } else if(inYears < 1.01){ document.write(Math.round(inDays) + " days ago"); } // in years else if(Math.round(inYears) == 1){ document.write("1 year ago"); } else { document.write(Math.round(inYears) + " years ago"); }