jeudi 11 février 2016

Rails convert datetimepicker date string to datetime data type

I am building a To Do List application with Ruby on Rails, and each item in my Task resource has a deadline attribute that is created with the gem 'datetimepicker'.

This 'datetimepicker' gem pulls in dates as a string data type with the format "12/13/2012", "%m/%d/%Y".

I am trying to group task elements by the day value in their deadline attribute. I've found one article on how to do this (although I think it contains one typo):

http://ift.tt/1o6Cja1

However, I'd rather do the work in the tasks_controller than the task model (maybe the model is the cleaner way to do it? I am a nuby and open to suggestions on this).

I've found another article on the group_by method that demonstrates an approximate process:

http://ift.tt/1Xlnv2V

This article looks a little cleaner to me. It requires me to use the .beginng_of_day method to treat all task items with the same day value in their deadline equally.

I'm running into an issue with both methods, which is that they treat deadline like a datetime data type. I want to use the .to_datetime method to convert task.deadline, but the 'datetimepicker' gem formats the deadline string in precisely the wrong way for .to_datetime to convert it:

"12/13/2012".to_datetime # => ArgumentError: invalid date

see => apidock[dot]com[slash]rails[slash]String[slash]to_datetime

I've found a similar article that recommends re-formatting the deadline attribute with the .strptime and .strftime methods, but I don't see how to do this when deadline is a string and not a datetime:

see => stackoverflow[dot]com[slash]questions[slash]16296885[slash]how-to-convert-datetime-picker-value-to-datetime-in-ruby-on-rails

Can someone help me make this conversion, or suggest a different (preferably simpler!) strategy for grouping tasks by day?

Thanks for your help, and apologies for the broken links; I don't have sufficient reputation points to embed more than 2 yet.

Aucun commentaire:

Enregistrer un commentaire