Created
May 5, 2012 02:14
-
-
Save larzconwell/2599109 to your computer and use it in GitHub Desktop.
Ruby natural language format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
class DateTime | |
def to_human(opts = {}) | |
date = self | |
today = opts[:today] || DateTime.now | |
# Difference between `today` and `date` | |
diff = (date.to_date - today.to_date).to_i | |
# How many days till the end of the week? | |
till_end_of_week = (6 - date.strftime("%w").to_i) | |
case diff | |
when 2 | |
"Day after tomorrow" | |
when 1 | |
"Tomorrow" | |
when 0 | |
"Today" | |
when -1 | |
"Yesterday" | |
when (1..(diff-till_end_of_week)+3) | |
# Works, mostly. A couple of issues when referencing dates past the current week | |
"This " + date.strftime("%A") | |
when ((diff-till_end_of_week)+3..(diff-till_end_of_week)+10) | |
"Next " + date.strftime("%A") | |
# Put last week here | |
else | |
date.strftime("%B %d, %Y %l:%M %p") | |
end | |
end | |
alias :to_natural :to_human | |
end | |
time = Time.now | |
date = DateTime.new(2012,5,16,time.strftime("%H").to_i,time.strftime("%M").to_i) | |
puts date.to_human(today: DateTime.new(2012,5,6,time.strftime("%H").to_i,time.strftime("%M").to_i)) | |
# Day of week date.strftime("%w") | |
# Day date.strftime("%A") | |
# Else format date.strftime("%B %d, %Y %l:%M %p") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment