I am posting a date to an API and the required format is as follows:
2014-12-01T01:29:18
I can get the date from the model like so:
Model.created_at.to_s
That returns:
2014-12-01 01:29:18 -0500
How can I use Rails or Ruby to format it like the required format with the T and removing the -0500?
Thanks
Use
where,
Following are some of the frequently used useful list of
Date
andTime
formats that you could specify instrftime
method:For the complete list of formats for
strftime
method please visit APIDockCreate an initializer for it:
Add something like this to it:
And then use it the following way:
⚠️ Your have to restart rails server for this to work.
Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s
Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under
config/locales/en.yml
(or whatever language), in your case like this:Or if you want to use this kind of format in a few specific places you can refer it as a variable like this
After that you can use it in your views like this:
Try this:
It's a time formatting function which provides you a way to present the string representation of the date. (http://ruby-doc.org/core-2.2.1/Time.html#method-i-strftime).
From APIdock: