Home > Mobile >  What is a simple way in Ruby to show the date and time?
What is a simple way in Ruby to show the date and time?

Time:09-12

I would like something in Ruby roughly equivalent to time.asctime() in Python:

import time
print(time.asctime())

outputs:

Sun Sep 11 10:12:48 2022

CodePudding user response:

puts Time.now.asctime

outputs:

Sun Sep 11 10:24:46 2022

CodePudding user response:

Simple String Output

Ruby supports lots of Time, Date, and DateTime objects and output formats. While I think the first answer is closer to the output format you want, the following is potentially simpler and possibly sufficient for many needs when just considering standard output or standard error:

p Time.now.to_s
#=> 2022-09-11 14:10:57 -0400

# using interpolation
p "Time: #{Time.now.to_s}"
#=> "Time: 2022-09-11 14:15:51 -0400"

Other Considerations

Note that if you want to use the results for any sort of comparison or calculation, you'll likely need to convert the result to one of the three object types described above. That's the main reason I mention them. Unless it's just printing to the screen, you should think about how you plan to use the result before deciding which of the objects will be most useful for you.

  • Related