루비 날짜 빼기 (예 : 90 일 전)
나는 다음의 joda-time API에 약간 망쳐졌습니다.
DateTime now = new DateTime();
DateTime ninetyDaysAgo = now.minusDays(90);
Ruby에서도 비슷한 작업을하려고하는데
now = Time.now
ninetyDaysAgo = now - (90*24)
그러나 수학은 여기서 벗어났습니다 (저는 자정에 데이트 작업을하고 있습니다).
날짜 빼기를위한 친숙한 API가 있습니까?
require 'date'
now = Date.today
ninety_days_ago = (now - 90)
IRB 콘솔을 통해 실행하면 다음과 같은 결과가 나타납니다.
>>require 'date'
now = Date.today
ninety_days_ago = (now - 90)
require 'date'
=> false
now = Date.today
=> #<Date: 2011-03-02 (4911245/2,0,2299161)>
ninety_days_ago = (now - 90)
=> #<Date: 2010-12-02 (4911065/2,0,2299161)>
시간이 필요하면 다음과 같이 말할 수 있습니다. now = DateTime.now
Rails를 사용하는 경우 다음을 확인하세요.
DateTime.now - 10.days
=> Sat, 04 May 2013 12:12:07 +0300
20.days.ago - 10.days
=> Sun, 14 Apr 2013 09:12:13 UTC +00:00
Rails를 사용 중이거나 ActiveSupport를 포함해도 괜찮다면 다음 과 같이 Numeric # days DSL을 사용할 수 있습니다 .
ruby-1.9.2-p136 :002 > Date.today
=> Wed, 02 Mar 2011
ruby-1.9.2-p136 :003 > Date.today - 90.days
=> Thu, 02 Dec 2010
시간 대신 날짜로 작업하기 때문에 Date 인스턴스로 시작하거나 DateTime 인텐스를 #to_date로 변환해야합니다. 날짜 인스턴스에서 숫자를 더하거나 빼면 숫자는 암시 적으로 일입니다.
ruby-1.9.2-p136 :016 > DateTime.now.to_date
=> #<Date: 2011-03-02 (4911245/2,0,2299161)>
ruby-1.9.2-p136 :017 > DateTime.now.to_date - 90
=> #<Date: 2010-12-02 (4911065/2,0,2299161)>
Ruby supports date arithmetic in the Date and DateTime classes, which are part of Ruby's standard library. Both those classes expose #+ and #- methods, which add and subtract days from a date or a time.
$ irb
> require 'date'
=> true
> (DateTime.new(2015,4,1) - 90).to_s # Apr 1, 2015 - 90 days
=> "2015-01-01T00:00:00+00:00"
> (DateTime.new(2015,4,1) - 1).to_s # Apr 1, 2015 - 1 day
=> "2015-03-31T00:00:00+00:00"
Use the #<< and #>> methods to operate on months instead of days. Arithmetic on months is a little different than arithmetic on days. Using Date instead of DateTime makes the effect more obvious.
> (Date.new(2015, 5, 31) << 3).to_s # May 31 - 3 months; 92 days diff
=> "2015-02-28"
Following your joda-time example, you might write something like this in Ruby.
now = DateTime.now
ninety_days_ago = now - 90
or maybe just
ninety_days_ago = DateTime.now - 90
use the number of seconds:
Time.now - 90*24*60*60
This is a super old post, but if you wanted to keep with a Time
object, like was originally asked, rather than switching to a Date
object you might want to consider using Ruby Facets
.
Ruby Facets is a standardized library of extensions for core Ruby classes.
http://rubyworks.github.io/facets/
By requiring Facets you can then do the following with Time objects.
Time.now.less(90, :days)
참고URL : https://stackoverflow.com/questions/5171102/ruby-date-subtraction-e-g-90-days-ago
'IT박스' 카테고리의 다른 글
Msysgit bash는 Windows 7에서 끔찍하게 느립니다. (0) | 2020.09.22 |
---|---|
시간을 형식으로 인쇄하는 방법 : 2009‐08‐10 18 : 17 : 54.811 (0) | 2020.09.22 |
인앱 구매를 테스트하려고 할 때 iTunes 계정 생성이 허용되지 않음 (0) | 2020.09.22 |
Python의 timeit으로 "글로벌 이름 'foo'가 정의되지 않았습니다."가져 오기 (0) | 2020.09.22 |
CSS hover vs. JavaScript mouseover (0) | 2020.09.22 |