HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyMinor

Adding time offsets to create future dates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
createdatestimeaddingfutureoffsets

Problem

How can I shorten this (working) code to create future dates in ruby for use as params in URLs?

I'm doing:

require 'cgi'
require 'time'

now=Time.new()
now_year=now.strftime('%Y').to_i
now_month=now.strftime('%m').to_i
now_day=now.strftime('%d').to_i
now_hour=now.strftime('%H').to_i

start_hour=(now_hour + 1)
end_hour=(now_hour + 2)

start_datetime=Time.new(now_year, now_month, now_day, start_hour)
end_datetime=Time.new(now_year, now_month, now_day, end_hour)

starts=CGI.escape(start_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"))
ends=CGI.escape(end_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"))


and it works, but it seems long and clumsy. Is there an easier way?

Solution

You can add seconds directly to a Time object, so you could do:

now = Time.now.utc
starts = now + 3600 # Add 1 hour's worth of seconds (60 * 60)
ends   = now + 7200 # Add 2 hours


and then do the strftime-formatting.

Of course, since you need to do this twice, I'd suggest adding a method to avoid the repetition, i.e.:

def offset_utc_timestamp(offset, format = "%Y-%m-%dT%H:%M:%S.%3NZ")
  time = Time.now.utc + offset
  time.strftime(format)
end


You may want to split it up differently (i.e. have the method just return a Time object, which you make into a string elsewhere; or have the method also do the URL escaping).

I'd also recommend using the URI.escape method instead, if this is intended for URLs

With all that your code becomes:

starts = URI.escape(offset_utc_timestamp(3600))
ends   = URI.escape(offset_utc_timestamp(7200))


Alternatively, the ActiveSupport gem has a ton of helpful time stuff, letting you do things like 2.hours.from_now.utc

Code Snippets

now = Time.now.utc
starts = now + 3600 # Add 1 hour's worth of seconds (60 * 60)
ends   = now + 7200 # Add 2 hours
def offset_utc_timestamp(offset, format = "%Y-%m-%dT%H:%M:%S.%3NZ")
  time = Time.now.utc + offset
  time.strftime(format)
end
starts = URI.escape(offset_utc_timestamp(3600))
ends   = URI.escape(offset_utc_timestamp(7200))

Context

StackExchange Code Review Q#47456, answer score: 7

Revisions (0)

No revisions yet.