Cette fonction adapte le texte de la date selon son ancienneté, avec une expression plus sympathique.
Exemples:
- 34 minutes ago
- Yesterday at 09:16 am
- Monday, 2nd April
A la question "pourquoi afficher une date en javascript plutôt que en dur dans le code HTML ?", je répondrais que çà permet d'adapter les heures au fuseau horaire de l'internaute ;o) .oO(étudiez l'astuce des SPAN avec la classe PubDate des Life-Lines)
Source / Exemple :
function elapsedTimeString(Day0)
{
var Days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var Months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var Year0 = Day0.getFullYear();
var MonthNr0 = Day0.getMonth()+1;
var DayNr0 = Day0.getDate();
var Hours0 = Day0.getHours();
var Minutes0 = Day0.getMinutes();
var Seconds0 = Day0.getSeconds();
var TimeStamp0 = Date.UTC(Year0,MonthNr0-1,DayNr0,Hours0,Minutes0,Seconds0);
var Day1 = new Date();
var Year1 = Day1.getFullYear();
var MonthNr1 = Day1.getMonth()+1;
var DayNr1 = Day1.getDate();
var Hours1 = Day1.getHours();
var Minutes1 = Day1.getMinutes();
var Seconds1 = Day1.getSeconds();
var TimeStamp1 = Date.UTC(Year1,MonthNr1-1,DayNr1,Hours1,Minutes1,Seconds1);
var Ecart = TimeStamp1 - TimeStamp0;
if (Ecart <= 0)
{
return 'today';
}
else if (Ecart <= 1000 * 60)
{
return Math.round(Ecart / 1000)+'s ago';
}
else if (Ecart <= 1000 * 60 * 60)
{
return Math.round(Ecart / (1000*60))+'min ago';
}
else if ((Ecart <= 1000 * 60 * 60 *24) && (DayNr1 == DayNr0))
{
ElapsedHours = Math.round(Ecart / (1000*60*60));
if (ElapsedHours == 1)
{
return '1 hour ago';
}
else
{
return ElapsedHours+'hours ago';
}
}
else
{
var HoursOP = Hours0;
var ampmOP = "am";
if (HoursOP == 0) HoursOP = 12;
if (HoursOP > 11)
ampmOP = "pm";
if (HoursOP > 12)
HoursOP -= 12;
HoursOP = leading2Zero(HoursOP);
var MinutesOP = leading2Zero(Minutes0);
if (Ecart <= (1000 * 60 * 60 * 24))
{
return 'yesterday at ' + HoursOP + ':' + MinutesOP + ' ' + ampmOP;
}
else
{
var DayName0 = Days[Day0.getDay()];
if (Ecart <= (1000 * 60 * 60 * 24 * 7))
{
return DayName0+' at ' + HoursOP + ':' + MinutesOP + ' ' + ampmOP;
}
else
{
var MonthName0 = Months[MonthNr0-1];
var DaySuffix = 'th';
if (DayNr0 == 1) DaySuffix = 'st'
else if (DayNr0 == 2) DaySuffix = 'nd'
else if (DayNr0 == 3) DaySuffix = 'rd';
if (Year0 == Year1)
{
return DayName0+', '+DayNr0+DaySuffix+' '+MonthName0;
}
else
{
return DayName0+', '+DayNr0+DaySuffix+' '+MonthName0+' '+Year0;
}
}
}
}
}
function leading2Zero(nr)
{
if (nr < 10) nr = "0" + nr;
return nr;
}
Conclusion :
Créé pour les besoins des profils LiFE-Line sur www.life2front.com