Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created August 23, 2012 17:57
Show Gist options
  • Save bjoerge/3439495 to your computer and use it in GitHub Desktop.
Save bjoerge/3439495 to your computer and use it in GitHub Desktop.
Spec
HumanDate.relative(DateTime.parse("August 23, 2012 00:00:00 UTC"), :today => DateTime.parse("2012-08-23")).should eq "i dag"
# encoding: utf-8
require 'active_support/time'
class HumanDate
# Month and day names
MONTHS_NO = %w(jan feb mar apr mai jun jul aug sep okt nov des)
MONTHS_LONG_NO = %w(januar februar mars april mai juni juli august september oktober november desember)
WEEKDAYNAMES_NO = %w(søndag mandag tirsdag onsdag torsdag fredag lørdag)
class << self
# Gir menneske-orienterte relative dato-angivelser. I morgen heter
# "i morgen", i går heter "i går" og lørdag neste uke heter "lørdag
# neste uke". onsdag 23. april 1974 derimot, heter "onsdag 23. april
# 1974".
#
# Støtter følgende options:
# <tt>:now</tt> - Hva skal den regne som "nå"? (default: Time.now)
# <tt>:shortmonths</tt> - Bruke tre bokstavers månedsnavn? (default: false)
def relative(date, options = {})
now = options[:today] || DateTime.now
shortmonths = options[:shortmonths]
monthnames = MONTHS_LONG_NO
monthnames = MONTHS_NO if shortmonths
if options[:absolute_date]
absolute_date = ', '+date.day.to_s+". "+monthnames[date.month-1]
else
absolute_date = ''
end
midnight = date.midnight
if midnight == (now - 1).midnight
"i går"+absolute_date
elsif midnight == now.midnight
"i dag"+absolute_date
elsif midnight == (now + 1).midnight
"i morgen"+absolute_date
elsif (now - 6 .. now + 6).include? date
if date < now
# "sist onsdag"
'sist '+WEEKDAYNAMES_NO[date.wday]+absolute_date
else
# "onsdag"
WEEKDAYNAMES_NO[date.wday]+absolute_date
end
elsif date.year == now.year
# "4. juni"
WEEKDAYNAMES_NO[date.wday]+" "+date.day.to_s+". "+monthnames[date.month-1]
else
# "4. juni 2005"
WEEKDAYNAMES_NO[date.wday]+" "+date.day.to_s+". "+monthnames[date.month-1]+" "+date.year.to_s
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment