DateTime substitution from a string in Ruby/Rails - ruby-on-rails

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

Related

How to use srtftime in views

I am getting an error with strftime.
My views look like:
<%=room.date%> which works and yields "2017-07-27".
However, I want to convert this to "July 27, 2017".
<%= Date.parse(room.date).strftime("%B %e, %Y ") %> does not work and causes the following error:
ActionView::Template::Error (no implicit conversion of Date into
String)
My schema is:
t.date "date"
I don't know what I am doing wrong. Thanks!
If your room.date is type of date you shouldn't try to parse it. So I'd suggest first try to use <%= room.date.strftime('%B %e, %Y'). Please comment below if that wont work.
Just to throw a different hat into the ring, you can also use
<%= l room.date, format: :long %>
which, by default, uses "%B %d, %Y" but can be easily changed by adding into your config/locales/en.yml.
en:
date:
formats:
long: "%B %e, %Y"
time:
formats:
long: "%B %e, %Y"
Use date: if it's a Date object or time: if it's DateTime or Time. This is short for I18n.l and looks like it works as far back a rails 3.2.13 at the least (it's hard to tell which rails you're using).
This way, if you ever want to support different locales the dates are all set up for it and, probably more importantly, it moves the date format out of your views, so if you ever decide you want a different format ("%A %B %e, %Y", for instance) you can change it in one place and all the views displaying dates get updated.
Note: If it is a Time or DateTime you might want to use instead
<%= l room.date, format: :date %>
and in config/locales/en.yml
en:
time:
formats:
date: "%B %e, %Y"
so your format: :long still shows the time portion when you want it to
It's asking for a String instead a Date data type, pass it a String, try with:
Date.parse(room.date.to_s).strftime("%B %e, %Y")
When room.date is a date, why do you want to parse it? You could use the Date directly.
Can you try:
<%= room.date.strftime("%B %e, %Y ") %>

Why does this work in console buy not in my app?

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.

Date-time picker formatting for Database input

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")

Assign new value to the fetched data from query in rails

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")

How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy) using Ruby on Rails

How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy) using Ruby on Rails?
Valid Ruby datetime formats
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Note that strptime is a part of Rails. And these are the relevant formats used:
%b - The abbreviated month name (``Jan'')
%d - Day of the month (01..31)
%m - Month of the year (01..12)
%y - Year without a century (00..99)
%Y - Year with century
You can do it with Date.parse and Date#strftime:
d = Date.parse('09-feb-73').strftime('%m/%d/%Y')
# "02/09/1973"
You could also use Date.strptime instead of Date.parse:
d = Date.strptime('09-feb-73', '%d-%b-%y').strftime('%m/%d/%Y')
# "02/09/1973"
The advantage of strptime is that you can specify the format rather than leaving it to parse to guess.
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Date Formats: http://snippets.dzone.com/posts/show/2255
If you require this in a view, I would suggest using localizations, since you can easily change the behavior based on your user's local settings and keep your controller code tidy (why should the controller care about the date format?). Example:
# config/locales/en.yml
en:
time:
formats:
short: "%m/%d/%Y"
# view file
<%=l Time.now, :format => :short %>
For more information on rails localizations, see the Rails Guide.

Resources