user3566591
user3566591

Reputation: 165

How to compare Time in Ruby?

I have the following ruby code:

session.each do |loads|
    time= session.GetTime
    puts time
end

This code returns multiple values:

2014-05-04T10:11:24.509-04:00

2014-03-04T11:01:39.242-04:00

2014-06-22T19:47:58.477-04:00

2014-02-21T23:56:25.869-04:00

I would like to compare the times and return only values greater than 2014-06-01. I get conversion errors if I just use >.

Any ideas?

Upvotes: 0

Views: 1124

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

Time.strptime is the workhorse method for parsing Time values:

require 'time'

TIME_SPLIT = Time.parse('2014-06-01')

times = %w[
  2014-05-04T10:11:24.509-04:00
  2014-03-04T11:01:39.242-04:00
  2014-06-22T19:47:58.477-04:00
  2014-02-21T23:56:25.869-04:00
].select{ |t| Time.strptime(t, '%FT%T.%L%z') > TIME_SPLIT }
# => ["2014-06-22T19:47:58.477-04:00"]

Time.parse is also useful, but it can be fooled by values that look like a MM/DD/YYYY form but are actually DD/MM/YYYY, where the date is greater than 12. Dates in the US are typically MM/DD/YYYY so people get confused when something like '12/31/2000' fails:

Time.parse('12/31/2000')
ArgumentError: argument out of range

The problem is, there is no month "31", it's a day.

Time.parse('31/12/2000')
# => 2000-12-31 00:00:00 -0700

Similarly, some dates could be nebulous and, as a result, be parsed incorrectly. If this date is from a US customer the month would be assumed to be first, but from another region it'd be the date:

Time.parse('01/02/2000') # => 2000-02-01 00:00:00 -0700

but, again, parse thought it was a day, so watch out.

Instead of letting parse try and possibly get it wrong or fail, it's better to define the formats your code can understand, look at the region the data comes from, then apply the appropriate format. These are two different ways of saying the same thing:

Time.strptime('2014-05-04T10:11:24.509-04:00', '%FT%T.%L%z') # => 2014-05-04 07:11:24 -0700
Time.strptime('2014-03-04T11:01:39.242-04:00', '%Y-%m-%dT%H:%M:%S.%L%z') # => 2014-03-04 08:01:39 -0700

And how to define whether the month is first or second:

Time.strptime('01/02/2001', '%m/%d/%Y') # => 2001-01-02 00:00:00 -0700
Time.strptime('01/02/2001', '%d/%m/%Y') # => 2001-02-01 00:00:00 -0700

You can find out more about strptime and the format strings in the documentation.

Upvotes: 1

Aguardientico
Aguardientico

Reputation: 7779

my_time = Time.new(2014, 06, 01)

then try

time >= my_time

Upvotes: 0

bryce
bryce

Reputation: 3051

Use Time.parse() on your time objects, it should convert them to more Ruby-friendly objects and allow you to compare them using > and <=, etc.

Upvotes: 0

Related Questions