Search code examples
ruby-on-railsdatetimemilliseconds

How do I get yesterday's time in milliseconds?


I'm running into a wall. I want to get yesterday's time in milliseconds. I thought the below would do the job

irb(main):001:0> yday = 1.day.ago
=> Tue, 03 Apr 2018 20:35:24 UTC +00:00
irb(main):002:0> yday.strftime('%Q').to_f
=> 0.0

but as you can see I'm getting a "0.0" for yesterday's time. How can I correct what I have to accurately get the time in milliseconds?


Solution

  • You have two options:

    (DateTime.now-1.day).strftime('%Q')
    

    Or:

    yday = 1.day.ago
    yday.to_datetime.strftime('%Q')
    

    Why you need to_datetime? Well, 1.day.ago is ActiveSupport::TimeWithZone which does not have %Q format (documentation) when strftime for DateTime does (documentation)