Home > database >  What is the best way to extract a numerical date from Ruby default date/time output?
What is the best way to extract a numerical date from Ruby default date/time output?

Time:10-07

I'm attempting to retrieve the date which is 24 hours ago.

time = Time.now.to_time - 24.hours
time.to_date
=> Wed, 05 Oct 2022 

I require it in the following format:

2022-10-05

Having read the Ruby time docs, and various questions here, I still haven't figured out the must succinct and clean way to go about this.

CodePudding user response:

When you have a Date object it is simply

puts Date.today - 1  # => 2022-10-05

With a Time Object , the - method subtracts seconds. So:

Time.now - 24*60*60

All this works without Rails.

CodePudding user response:

You can rebuild any value with specific date methods :

Time.now.day 
=> 6

Time.now.month
=> 10

Time.now.year
=> 2022

So doing something like

formatted_date = "#{time.year}-#{time.month}-#{time.day}"

should work

Also you can check strftime() method documented here : https://apidock.com/ruby/DateTime/strftime. It seems your format is included in ISO8601 formats : time.strftime("%F")

CodePudding user response:

How about this?

Date.yesterday.to_s #=> "2022-10-5"
  • Related