t56k
t56k

Reputation: 6981

Rails DateTime gives invalid date sometimes and not others

I've got a bunch of user-inputted dates and times like so:

date = "01:00pm  06/03/2015"

I'm trying to submit them to a datetime column in a database, and I'm trying to systemize them like this:

DateTime.strptime(date, '%m/%d/%Y %H:%M')

But I consistently get an invalid date error. What am I doing wrong? If I submit the string without strptime the record will save but it sometimes gets the date wrong.

Also, how can I append a timezone to a DateTime object?

Edit:

So .to_datetime and DateTime.parse(date) work for the date string and fail for date2. What's going on?

date2 = "03:30pm 05/28/2015"

Upvotes: 1

Views: 3222

Answers (3)

shivam
shivam

Reputation: 16506

Try using to_datetime:

date.to_datetime
# => Fri, 06 Mar 2015 13:00:00 +0000

Also if you read the documentation for DateTime#strptime, here. It states:

Parses the given representation of date and time with the given template, and creates a date object.

Its important to note that the template sequence must match to that of input string sequence, which don't in your case - leading to error.

Update

Using to_datetime over second example will generate

ArgumentError: invalid date

This is because it expects the date to be in dd-mm-yy format. Same error will be raised for DateTime.parse as to_datetime is nothing but an api for the later. You should use strptime in-case of non-standard custom date formats. Here:

date2 = "03:30pm 05/28/2015"
DateTime.strptime(date2, "%I:%M%p %m/%d/%Y")
# => Thu, 28 May 2015 15:30:00 +0000

Upvotes: 2

kaybee99
kaybee99

Reputation: 4744

You haven't got your parameters in the correct order.

DateTime.strptime(date, '%H:%M%p %m/%d/%Y')

You'll also need to add %p for the am/pm suffix

Upvotes: 0

pangpang
pangpang

Reputation: 8821

date = "01:00pm  06/03/2015"    
DateTime.parse(date)
=> Fri, 06 Mar 2015 13:00:00 +0000

Upvotes: 1

Related Questions