Skip to content

Instantly share code, notes, and snippets.

@anderssvendal
Created November 2, 2011 08:15
Show Gist options
  • Save anderssvendal/1333152 to your computer and use it in GitHub Desktop.
Save anderssvendal/1333152 to your computer and use it in GitHub Desktop.
Relative time formatting
TimeFormatter =
to_pretty: (date)->
now = new Date()
date = new Date(date)
# Time ago in seconds
a = (now - date) / 1000
if a is 0 then 'akkurat nå'
else if a is 1 then 'ett sekund siden'
else if 2 <= a <= 59 then "#{Math.round(a)} sekunder siden"
else if 60 <= a <= 119 then "ett minutt siden"
else if 120 <= a <= 3540 then "#{Math.round(a / 60)} minutter siden"
else if 3541 <= a <= 7100 then "en time siden"
else if 7101 <= a <= 82800 then "#{Math.round((a + 99) / 3600)} timer siden"
else if 82801 <= a <= 172000 then "en dag siden"
else if 172001 <= a <= 518400 then "#{Math.round((a + 800) / (60 * 60 * 24))} dager siden"
else "#{Math.round((a + 180000) / (60 * 60 * 24 * 7))} uker siden"
<?php
class TimeFormatter {
private $datetime;
public static function to_pretty($datetime) {
$datetime = new DateTime($datetime);
$now = new DateTime();
$interval = $now->diff($datetime);
$seconds_ago = self::interval_to_seconds($interval);
if ($seconds_ago == 0) {
return 'akkurat nå';
}
if ($seconds_ago == 1) {
return 'ett sekund siden';
}
else if(self::in_range($seconds_ago, 2, 59)) {
return $seconds_ago.' sekunder siden';
}
else if(self::in_range($seconds_ago, 60, 119)) {
return 'ett minutt siden';
}
else if(self::in_range($seconds_ago, 120, 3540)) {
return round($seconds_ago / 60).' minutter siden';
}
else if(self::in_range($seconds_ago, 3541, 7100)) {
return "en time siden";
}
else if(self::in_range($seconds_ago, 7101, 82800)) {
return round(($seconds_ago + 99) / 3600).' timer siden';
}
else if(self::in_range($seconds_ago, 82801, 172000)) {
return "en dag siden";
}
else if(self::in_range($seconds_ago, 172001, 518400)) {
return round(($seconds_ago + 800) / (60 * 60 * 24)).' dager siden';
}
else if(self::in_range($seconds_ago, 518401, 1036800)) {
return "en uke siden";
}
return round(($seconds_ago + 180000) / (60 * 60 * 24 * 7)).' uker siden';
}
private static function interval_to_seconds($interval) {
return ($interval->y * 365 * 24 * 60 * 60) +
($interval->m * 30 * 24 * 60 * 60) +
($interval->d * 24 * 60 * 60) +
($interval->h * 60 *60) +
($interval->i * 60) +
$interval->s;
}
private static function in_range($i, $from, $to) {
return $i >= $from && $i <= $to;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment