给定一个时间戳,如何确定几周前?

问题描述 投票:1回答:2

我希望返回自我的应用程序中创建用户以来的周数。

我的模型是User.rb(id,created_at)

鉴于user.created_at

2.4.0 :008 > user.created_at
 => Mon, 14 Aug 2017 15:51:23 UTC +00:00 

我怎么能这样做:user.created_at.weeks_ago返回一个整数,表示自用户创建以来的周数?

ruby-on-rails ruby ruby-on-rails-5
2个回答
2
投票

如果你只是想建立一个人性化的字符串,我相信time_ago_in_words就是你追求的。

https://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words

否则,我会采取以下的方式:

(Time.new - user.created_at) / 1.week

如果你想要一个更优雅的解决方案,Subtract dates in Ruby and get the difference in minutes提到the Time Difference gem for Ruby

EG

TimeDifference.between(user.created_at.to_time, Time.now).in_weeks

1
投票

我会用:

Time.current
 => Wed, 20 Sep 2017 03:56:15 UTC +00:00 

然后

((Time.current - person.created_at)/604800).to_i

减法为您提供秒数,然后除以604800,即一周中的秒数。

© www.soinside.com 2019 - 2024. All rights reserved.