2010-04-20 43 views
5

Có đá quý ruby ​​sẽ định dạng ngày tháng tương ứng với thời gian hiện tại không? Tôi muốn sản lượng như "Ngày mai lúc 5 giờ chiều", "Thứ năm tuần sau lúc 5:15 chiều", tôi không quá lo lắng về kết quả chính xác, miễn là ngày tương đối bằng ngôn ngữ tự nhiênĐịnh dạng ngày tương đối

Trả lời

7

nếu bạn có đường ray, Tôi nghĩ rằng ActionView::Helpers::DateHelper#distance_of_time_in_words sẽ giúp điều đó.

require 'rubygems' 
require 'action_view' 
include ActionView::Helpers::DateHelper 

from_time = Time.now 
distance_of_time_in_words(from_time, from_time + 50.minutes)  # => about 1 hour 
distance_of_time_in_words(from_time, 50.minutes.from_now)   # => about 1 hour 
distance_of_time_in_words(from_time, from_time + 15.seconds)  # => less than a minute 
distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds 
distance_of_time_in_words(from_time, 3.years.from_now)    # => over 3 years 
distance_of_time_in_words(from_time, from_time + 60.hours)   # => about 3 days 
distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute 
distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute 
distance_of_time_in_words(from_time, 76.seconds.from_now)   # => 1 minute 
distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year 
distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years 

to_time = Time.now + 6.years + 19.days 
distance_of_time_in_words(from_time, to_time, true)  # => over 6 years 
distance_of_time_in_words(to_time, from_time, true)  # => over 6 years 
distance_of_time_in_words(Time.now, Time.now)   # => less than a minute 

Trong trường hợp liên quan đến thời điểm hiện tại, sử dụng distance_of_time_in_words_to_now thay vì distance_of_time_in_words.

Nếu ứng dụng của bạn là dựa trên đường ray, chỉ cần sử dụng distance_of_time_in_words, distance_of_time_in_words_to_now, time_ago_in_words trong chế độ xem.

+0

Chỉ cần những gì tôi cần, nhưng không sử dụng đường ray: (Bất kỳ ý tưởng nào nếu thành phần Rails có sẵn bên ngoài đường ray? –

+0

Tôi nghĩ rằng mã trên sẽ hoạt động không có đường ray, sau khi cài đặt gói hành động (gem install actionpack), nhưng không – unsouled

+0

@unsouled - Đã xác nhận – steenslag

-3

thử đá quý 'mãn tính'

nó thực hiện chính xác những gì bạn yêu cầu.

+1

có vẻ như ngược lại: nó phân tích cú pháp thời gian, nó không định dạng chúng. –