I'm trying to format the date which is received from the query in rails but the value is not updated.
Here is my code :-
#data = "My query"
#data.each do |eventdata|
eventdata.start_date = eventdata.start_date.strftime("%Y-%m-%d %I:%M %p")
puts "*******************"+eventdata.start_date.to_s
eventdata.end_date = eventdata.end_date.strftime("%Y-%m-%d %I:%M %p")
end
The date received from my ajax call is in this format '2012-12-06T00:00:00+05:30',it is not updated. What could be the issue?
Also the event value printed on my console is ******************2012-12-06 00:00:00 +0530
Try
eventdata.start_date.strftime("%Y-%m-%d %I:%M:%p")
or
eventdata.start_date.strftime("%Y-%m-%d %H:%M:%S")
Related
I tried to solve this problem a thousand different ways looking at dozens of StackOverflow posts as well as outside tutorials dealing with DateTime, bootstrap datetimepicker, formatting, strptime, strftime, and on and on, without resolution. I have one basic question right now that may help me move forward.
Why does this work in my console:
DateTime.strptime("09-29-2016 03:29 PM", "%m-%d-%Y %I:%M %p")
=> Thu, 29 Sep 2016 15:29:00 +0000
But this fails in my app:
#image.start_at = DateTime.strptime(params[:start_at].to_s, "%m-%d-%Y %I:%M %p")
=>ArgumentError in ImagesController#create
invalid date
My start_at parameters come through as:
..."start_at"=>"09-29-2016 03:29 PM"},...
Also, this doesn't work in my app:
#image.start_at = DateTime.strptime(#image.start_at.to_s, "%m-%d-%Y %I:%M %p")
This should work just fine:
#image.start_at = Date.strptime(params[:image][:start_at], "%m-%d-%Y %I:%M %p")
Explanation:
you do not have to convert it to string - anything in params IS a String;
since the start_at's type is a Date, you should pass a Date object to it, not a DateTime object.
If your start_at IS a datetime type (not date, as you've said in comments),
#image.start_at = DateTime.strptime(params[:image][:start_at], "%m-%d-%Y %I:%M %p")
will work.
Imagine that I have this string coming from some external api. The string format is always same including the HTML tags and everything.
"<p>The update time is <strong>Tuesday 04/28/15 08:30 AM PDT</strong>, please disregard the old timing.</p>"
How do I extract the DateTime from the string (Tuesday 04/28/15 08:30 AM PDT) and convert it to EST and then wrap it back to string around the <strong> tags?
If the string is exactly the same every time, I would just gsub out the parts of the string you don't want.
string_from_api.gsub!(/(.*<strong>|<\/strong>.*)/, '')
Then use strptime like so:
date_time = DateTime.strptime(string_from_api, "%A %m/%d/%y %I:%M %p %Z")
(My favorite strftime resource.)
Then, assuming you're using Rails, you can change the timezone with
est_time = date_time.in_time_zone('EST')
Then you just have to put it all back together:
time_formatted = est_time.strftime("%A %m/%d/%y %I:%M %p %Z")
"<p>The update time is <strong>#{time_formatted}</strong></p>"
def convert_time_message(message)
regex = /<strong\>(.*?)\<\/strong>/
time_format = '%a %m/%d/%y %H:%M %p %Z'
parsed_time = DateTime.strptime(message.match(regex)[1], time_format)
converted_time = parsed_time.in_time_zone('EST')
message.gsub(regex, "<strong>#{converted_time.strftime(time_format)}</strong>")
end
convert_time_message("<p>The update time is <strong>Tuesday 04/28/15 08:30 AM PDT</strong>, please disregard the old timing.")
You should be able to use DateTime.strptime to parse the date you've been given and then DateTime.strftime to output it again once you've modified it to your satisfaction. Something like:
s = "<p>The update time is <strong>Tuesday 04/28/15 08:30 AM PDT</strong>, please disregard the old timing."
s.sub(/<strong>(.*)<\/strong>/) do |s|
# Parse the date in between the <strong> tags
in_date = DateTime.strptime($1, "%A %m/%d/%y %I:%M %p %Z")
edt_time = in_date + 3.hours
"<strong>#{edt_time.strftime("%A %m/%d/%y %I:%M %p EDT")}</strong>"
end
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.
I want to convert a jquery datetime picker in to a db input. But
"10/24/2013 12:00 am +0300".to_datetime.utc.strftime("%Y-%m-%d %H:%M:%S")
Give me an error;
ArgumentError: invalid date
How can i get it to work.
"10/24/2013 12:00 am +0300" is just an example of the input not just one specific input am working with.
I wish for something that can work better than this
schedule = params[:message][:schedule].to_dateime.utc.strftime("%Y-%m-%d %H:%M:%S")
Thank you everyone, i hope this works;
schedule = params[:message][:schedule]
scheduled_time = DateTime.strptime("#{schedule}","%m/%d/%Y %H:%M %p %z").to_datetime.utc.strftime("%Y-%m-%d %H:%M:%S")
You could use strptime to specify the format of the string for parsing:
DateTime.strptime "10/24/2013 12:00 am +0300", "%m/%d/%Y %H:%M %p %z"
You can try this
Time.new("10/24/2013 12:00 am +0300").utc.strftime("%Y-%m-%d %H:%M:%S")
Try following
You need to understand in which format you are getting your date-time
In given example it is in the format "%m/%d/%Y %H:%M %p %z"
Ref this for its meaning
DateTime.strptime("10/24/2013 12:00 am +0300", "%m/%d/%Y %H:%M %p %z").to_datetime.utc.strftime("%Y-%m-%d %H:%M:%S")
I currently have a form that uses select_date Date.today When I view the form I can select options such as January 3, 2012. Although when I post the value, it reads 2013-01-03 00:00:00
In the create action the parameters for the Show's date is as followed:
#show.date = Date.civil(params[:date][:year].to_i,
params[:date][:month].to_i,
params[:date][:day].to_i)
How might I get this to read as it read when I selected the date, aka "January 3, 2013"?
Thanks for your help.
One answer is to call date.strftime passing in the format string "%B %d, %Y" wherever you want to display the date. (You can use "%B %-d, %Y" if you don't want day to be zero-padded):
Show: <%= date.strftime("%B %d, %Y") %>