简体   繁体   中英

How to change Rails default time format?

I am using this guide, http://blog.nicoschuele.com/posts/cheatsheet-to-set-app-wide-date-and-time-formats-in-rails , and it doesn't seem to be working.

Currently, whenever I make a JSON request and get back data my created_at and other time fields show iso8601 format.

An example of the format is 2014-10-23T00:35:14.800Z . I would prefer something more readable like Sun, 3 Nov 2013 14:22:18 -0700

I did what the guide above said to do, but when I restart my server and fire off the request again, the JSON still returns the data in iso8601 format.

How do I remedy this?

I don't recommend it but you can set it Rails wide as you've requested at this link: http://blog.nicoschuele.com/posts/cheatsheet-to-set-app-wide-date-and-time-formats-in-rails


I'll give you what I used for my html DateTime conversion. I do not have a JSON answer, but I hope this'll give you the answer you're looking for. I agree with Nils Landt in

You do not want to change the time format in the API. Keep it as ISO 8601, and change it on the client side. Way less hassle all around.

Here's what I put in my controller:

before_action :correct_datetime, only: [:create, :update]
def correct_datetime
  params['event']['starts_at'] = DateTime.strptime(params['event']['starts_at'],'%m/%d/%Y %l:%M %p') unless params['event'].try {|i| if i.try(:has_key?, 'starts_at'); i['starts_at'].empty?; else; true; end }
  params['event']['ends_at'] = DateTime.strptime(params['event']['ends_at'],'%m/%d/%Y %l:%M %p') unless params['event'].try {|i| if i.try(:has_key?, 'ends_at'); i['ends_at'].empty?; else; true; end }
end

And in my view I'm using Bootstrap DateTimePicker for some text areas.

Starts at: <%= f.text_field :starts_at, value: (f.object.starts_at.strftime('%m/%d/%Y %l:%M %p') if f.object.starts_at), class: 'form-control', style: 'width:300px;' %>
Ends at: <%= f.text_field :ends_at, value: (f.object.ends_at.strftime('%m/%d/%Y %l:%M %p') if f.object.ends_at), class: 'form-control', style: 'width:300px;' %>

To allow the datetime picker to work I use the following in my event.js.coffee CoffeeScript file:

$ ->
  $("#event_starts_at").datetimepicker()
  $("#event_ends_at").datetimepicker()
  return

I apologize that I don't have the JSON results for this. But I have given you the input and output formatting methods for accomplishing what you seek.

To convert from a DateTime object from the DB you use strftime . And to format it back to save in the DB you use strptime .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM