qichunren
qichunren

Reputation: 4475

How to judge whether a time/date is today, in ruby?

I have a settlement, I want to judge if the return_service_date is today, how to do this?

This is my code (rails):

if settlement.return_service_date && 
   settlement.return_service_date.to_s(:date) == Time.now.to_s(:date)

Is there a better way to do this?

Upvotes: 12

Views: 4327

Answers (2)

molf
molf

Reputation: 74935

In Rails, you can do:

settlement.return_service_date.today?

Upvotes: 22

maddin2code
maddin2code

Reputation: 1354

For everyone who isn't using rails, my plain ruby solution with Time looks like the following, if you have Dates instead of Times you can convert them with .to_time()

    # current time
    time = Time.new()

    # some time
    some_time = Time.new() + 7550

    # set beginning of today
    today_start =  Time.new(time.year,time.month,time.day)

    # set ending of today
    today_end =  today_start + 86399

    # check if some_time is in between today start and end
    puts (today_start..today_end).cover?(some_time)

Depending on your current time it prints true (if your day still has at least 7550 seconds left) or false.

Upvotes: 9

Related Questions