0

I'm using the Rspotify gem and trying to compare the date I get back for a given album (i.e. album.release_date) with the current user's last sign in date (i.e. current_user.last_sign_in_at). The release_date is a string.

Example album release date: "2017-03-18"

Example last sign in date: Sat, 13 May 2017 18:57:28 UTC +00:00

I've looked at and tried every solution I could find online, including:

  • Various string to date methods (e.g. DateTime(), .to_time, etc.)
  • Converting the string to a date and then both dates to integers
  • Adding a time zone

But I keep running into a couple errors.

The two most common errors I get are argument out of range and invalid date. I'm further confused because, in the console when using byebug, I'm able to compare the two dates with a few different conversion methods.

Spencer K.
  • 459
  • 1
  • 9
  • 24
  • Ref :- http://stackoverflow.com/questions/2955830/how-to-check-if-a-string-is-a-valid-date – Salil May 16 '17 at 06:05

3 Answers3

1

You just need to convert both the formats to date

"2017-03-18".to_date > "Sat, 13 May 2017 18:57:28 UTC +00:00".to_date
#=> false

And you can compare the dates

Same with time

"2017-03-18".to_time > "Sat, 13 May 2017 18:57:28 UTC +00:00".to_time
#=> false
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
  • If I use `to_date`, I get an `invalid date` error. If I use `to_time`, I get an `argument out of range` error. It looks like it's only happening when converting the `album.release_date`, though -- the `last_sign_in_at` is fine. – Spencer K. May 16 '17 at 15:47
  • When I use `to_time`, this is the format for the `release_date`: `2017-03-18 00:00:00 +0000`, and this is the format for the `last_sign_in_at`: `2017-05-13 18:57:28 +0000`. And when I use `to_date`, this is the format for the `release_date`: `Sat, 18 Mar 2017`, and this is the format for `last_sign_in_at`: `Sat, 13 May 2017`. How else should I make sure the date format is proper? – Spencer K. May 17 '17 at 04:51
0

I hadn't accounted for strings without months or days (e.g. '2010' or '2010-10').

Spencer K.
  • 459
  • 1
  • 9
  • 24
-1

Try and see .strftime('%Y-%m-%d'). It returns only the year, month and date and now the dates can be compared.

Ananthi
  • 413
  • 7
  • 13