Question

I need to get three dates in variables

Today Since Midnight which I have as

t = Time.now.strftime("%Y-%m-%d 00:00:01") # 2012-11-19 00:00:01

Yesterday Since Midnight (i.e. 00:00:00 to 23:59:59)

y1 = 2012-11-18 00:00:01
y2 = 2012-11-19 23:59:59

it is specifically the y1 & y2 variables I need to create as strings for use in a gem. being new to ruby I am a little confused as Time.yesterday doesn't seem to do what I need

EDIT

For this be sure to include

require 'active_support/all'

and ensure the gem is bundled for your application.

Used:

@current   = (Time.now).beginning_of_day.utc.strftime("%Y-%m-%d")
@yesterday = (Time.now - 1.day).beginning_of_day.utc.strftime("%Y-%m-%d")
@everything = (Time.now - 2.day).end_of_day.utc.strftime("%Y-%m-%d")
Was it helpful?

Solution

You can do,

 t=Time.now
 y1=t-1.day
 y2=t+1.day

OTHER TIPS

t = Time.now
t - 1.day # => yesterday
t + 1.day # => tomorrow

convert t to date first,

t = t.to_date

t - 1.day # => yesterday
t + 1.day # => tomorrow

Since you are running Rails there's help to get from ActiveSupport

1.day.ago.midnight
Time.new.beginning_of_day

You should also consider not using 2012-11-19 00:00:01 or 2012-11-19 23:59:59. Instead you could use 00:00:00 and compare with >= or < depending on what you want to achieve. If you always round to seconds then 2012-11-19 00:00:00 to 2012-11-19 23:59:59 would work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top