Reputation: 12072
How do you format moment()
to Rails datetime?
Im using react-datepicker and Rails 5 as the back end.
React:
let newDate = this.state.startDate.format('YYYY-MM-DD HH:mm')
console.log(newDate); #=> 2016-10-11 08:46
Looking at the momentjs formats, I see nothing close to rails datetime format ie: Mon, 10 Oct 2016 15:16:29 UTC +00:00
The aim is to pass newDate
as params
to a rails controller: params[:new_date]
Update:
cema-sp's answer was the final part to my answer but I was getting errors. To solved this:
# JS:
let newDate = this.state.startDate.format(); # no format type
# Controller:
DateTime.strptime(params[:new_date], '%Y-%m-%dT%H:%M:%S%z')
Upvotes: 2
Views: 4569
Reputation: 382
moment.js object newDate
may be formatted in any string you like (for example like in the question YYYY-MM-DD HH:mm
or default format) and sent to the server:
const newDate = this.state.startDate.format()
...
fetch(apiEndpointUrl, {
method: 'POST',
body: JSON.stringify({
new_date: newDate,
})
}).then(...)
...
The only thing is that you have to parse params[:new_date]
on the Rails backend.
Use simple DateTime class parse
method or more performant strptime
(provide it choosen format).
If you want to update model you may use setter method:
def new_date=(value)
parsed = if value.is_a? String
DateTime.parse(value)
# Or more performant
# DateTime.strptime(value, '%Y-%m-%dT%H:%M:%S%z')
else
value
end
write_attribute(:new_date, parsed)
end
If you need to work with the date in controller, just parse it with one of DateTime methods:
new_date = DateTime.parse(params[:new_date])
# Or
new_date = DateTime.strptime(params[:new_date], '%Y-%m-%dT%H:%M:%S%z')
Upvotes: 6