Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

time - How do you say something happened "x minutes ago" or "x hours ago" or "x days ago" in Ruby?

If I have a time variable in Ruby, how could I say that it refers to an event that happened one of the following:

"x minutes ago" or "x hours ago" or "x days ago"

Obviously if something happened 2 days ago, I would not want to say it happened such-and-such minutes ago.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's the language agnostic version which you should be able to convert into any language:

ONE_MINUTE = 60
ONE_HOUR = 60 * ONE_MINUTE
ONE_DAY = 24 * ONE_HOUR
ONE_WEEK = 7 * ONE_DAY
ONE_MONTH = ONE_DAY * 3652425 / 120000
ONE_YEAR = ONE_DAY * 3652425 / 10000

def when(then):
    seconds_ago = now() - then

    if seconds_ago < 0:
        return "at some point in the future (???)"
    if seconds_ago == 0:
        return "now"

    if seconds_ago == 1:
        return "1 second ago"
    if seconds_ago < ONE_MINUTE:
        return str(seconds_ago) + " seconds ago"

    if seconds_ago < 2 * ONE_MINUTE:
        return "1 minute ago"
    if seconds_ago < ONE_HOUR:
        return str(seconds_ago/ONE_MINUTE) + " minutes ago"

    if seconds_ago < 2 * ONE_HOUR:
        return "1 hour ago"
    if seconds_ago < ONE_DAY:
        return str(seconds_ago/ONE_HOUR) + " hours ago"

    if seconds_ago < 2 * ONE_DAY:
        return "1 day ago"
    if seconds_ago < ONE_WEEK:
        return str(seconds_ago/ONE_DAY) + " days ago"

    if seconds_ago < 2 * ONE_WEEK:
        return "1 week ago"
    if seconds_ago < ONE_MONTH:
        return str(seconds_ago/ONE_WEEK) + " weeks ago"

    if seconds_ago < 2 * ONE_MONTH:
        return "1 month ago"
    if seconds_ago < ONE_YEAR:
        return str(seconds_ago/ONE_MONTH) + " months ago"

    if seconds_ago < 2 * ONE_YEAR:
        return "1 year ago"
    return str(seconds_ago/ONE_YEAR) + " years ago"

Note that the year/month figures are approximate (based on averages) but that shouldn't really matter since the relative error will still be very low.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...