How do you do relative time in Rails?

前端 未结 11 1542
借酒劲吻你
借酒劲吻你 2020-12-02 03:43

I\'m writing a Rails application, but can\'t seem to find how to do relative time, i.e. if given a certain Time class, it can calculate \"30 seconds ago\" or \"2 days ago\"

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 04:27

    If you're building a Rails application, you should use

    Time.zone.now
    Time.zone.today
    Time.zone.yesterday
    

    This gives you time or date in the timezone with which you've configured your Rails application.

    For example, if you configure your application to use UTC, then Time.zone.now will always be in UTC time (it won't be impacted by the change of British Summertime for example).

    Calculating relative time is easy, eg

    Time.zone.now - 10.minute
    Time.zone.today.days_ago(5)
    

提交回复
热议问题