Ruby / Rails:将日期时间转换为自然语言(例如2012年3月23日至“本周五”) [英] Ruby/Rails: Converting datetime to natural language (e.g. 3/23/2012 to "this Friday")
问题描述
- 3/23/2012至本周五
- 3/26/2012至下周一
- 3/31/2012至下周末
- 4 / 15/2012至下个月
- 3/15/2012至上周四
- 3/01/2011至去年
基本上,我正在寻找与慢性宝石。更类似于 distance_of_time_in_words
,但有一个扭曲。而不是从数据库中获取日期并按原样显示,我希望使它们在显示给最终用户时更加人性化,更加友好。
这是一个小小的黑客,完全没有完成和不合适。但是Ruby / Rails是非常棒的日期,范围是如此完美,也许如果你没有找到宝石,这样的事情会让你开始:
module HumanDate
def date_difference_for_people(from,to)
seconds_in_day = 24 * 60 * 60
days_difference =((to - from)/ seconds_in_day).round
case days_difference
当-1
昨天
当0
今天
当1
明天
当2..days_left_in_week
this#{day_name(difference)}
when(days_left_in_week + 1)..(days_left_in_week + 7)
next week
when(days_left_in_week + 8).. days_left_in_month
本月晚些时候
else
以后 - 剩下多少:-)
end
end
def day_name(days_from_now)
days_from_now.days_from_now.strftime(%A)
end
def days_left_in_month
时间。 now.end_of_month.day - Time.now.day
end
def days_left_in_week
Time.now.end_of_week.day - Time.now.day
end
end
Is anyone aware of a gem, method, or code snippet that will convert datetime values into sometime more human-friendly without having to create a series of rules or put a bunch of logic in the view? For example: if today is 3/19/2012, convert:
- 3/23/2012 to "This Friday"
- 3/26/2012 to "Next Monday"
- 3/31/2012 to "Next weekend"
- 4/15/2012 to "Next month"
- 3/15/2012 to "Last Thursday"
- 3/01/2011 to "Last year"
Basically, I’m looking for the opposite of the Chronic gem. Something more similar to the distance_of_time_in_words
, but with a twist. Instead of taking dates from the database and displaying them as-is, I’d like to make them more human-friendly and relatable when displayed to the end user.
This is a little hack, totally unfinished and inelegant. But Ruby/Rails is so awesome with dates, and ranges are so perfect, maybe if you don't find the gem, something like this will get you started:
module HumanDate
def date_difference_for_people (from, to)
seconds_in_day = 24 * 60 * 60
days_difference = ((to - from)/seconds_in_day).round
case days_difference
when -1
"yesterday"
when 0
"today"
when 1
"tomorrow"
when 2..days_left_in_week
"this #{day_name(difference)}"
when (days_left_in_week + 1)..(days_left_in_week + 7)
"next week"
when (days_left_in_week + 8)..days_left_in_month
"later this month"
else
"later -- how much left to you :-)"
end
end
def day_name(days_from_now)
days_from_now.days_from_now.strftime("%A")
end
def days_left_in_month
Time.now.end_of_month.day - Time.now.day
end
def days_left_in_week
Time.now.end_of_week.day - Time.now.day
end
end
这篇关于Ruby / Rails:将日期时间转换为自然语言(例如2012年3月23日至“本周五”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!