I wrote a function
toBeautyString(epoch) : String
which given a epoch
, return a string which will display the relative time from now in hour and minute
For instance:
// epoch: 1346140800 -> Tue, 28 Aug 2012 05:00:00 GMT
// and now: 1346313600 -> Thu, 30 Aug 2012 08:00:00 GMT
toBeautyString(1346140800)
-> "2 days and 3 hours ago"
I want now to extend this function to month and year, so it will be able to print:
2 years, 1 month, 3 days and 1 hour ago
Only with epoch without any external libraries. The purpose of this function is to give to the user a better way to visualize the time in the past.
I found this: Calculate relative time in C# but the granularity is not enough.
function toBeautyString(epochNow, epochNow){
var secDiff = Math.abs(epochNow - epochNow);
var milliInDay = 1000 * 60 * 60 * 24;
var milliInHour = 1000 * 60 * 60;
var nbDays = Math.round(secDiff/milliInDay);
var nbHour = Math.round(secDiff/milliInHour);
var relativeHour = (nbDays === 0) ? nbHour : nbHour-(nbDays*24);
relativeHour %= 24;
if(nbHour === 0){
nbDays += 1;
}else if(nbHour === (nbDays-1)*24){
nbDays -= 1;
}
var dayS = (nbDays > 1) ? "days" : "day";
var hourS = (relativeHour > 1) ? "hours" : "hour";
var fullString = "";
if(nbDays > 0){
fullString += nbDays + " " + dayS;
if(relativeHour > 0)
fullString += " ";
}
if(relativeHour > 0){
fullString += relativeHour + " " + hourS;
}
if(epochDate > epochNow){
return "Will be in " + fullString;
}else if ((epochDate === epochNow)
|| (relativeHour === 0 && nbDays === 0)){
return "Now";
}else{
return fullString + " ago";
}
}