简体   繁体   中英

Ruby: how to parse string '3 days ago'?

Given an input string like 3 days ago , how can I turn it into a date attribute?

Maybe something like DateTime.parse('3 days ago') ?

With rails there is no way to do that. You'll need to create a custom parser or use an already created solution as chronic or chronic_duration

Using chronic it would be as simple as your suggestion

Chronic.parse('3 days ago')
=> 2020-01-10 19:28:18 UTC

If you are using Ruby on Rails you have the syntax '...ago' for date and time, eg:

3.hours.ago, 1.day.ago, etc.

So you can replace the spaces for dots and eval the string, eg:

> eval('2 days ago'.tr!(' ', '.'))
Sun, 12 Jan 2020 13:37:00 UTC +00:00

As an option, in case if you will use rails and you don't need all other functionality of chronic , you can write something like this:

def parse_date(string)
  date, *options = string.split(' ')
  options.inject(date.to_i) do |date, option|
    date.public_send(option)
  end
end

You could get the current date as a UNIX timestamp (milliseconds or seconds since 1970 Jan 1), and then minus 3 days (also as a Unix timestamp) from it.

ie

today = Time.now.to_i
three_days = 86400*3
three_days_ago_unix = today - three_days
three_days_ago_date = Time.at(three_days_ago)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM