Looking for the best way to convert a string like "01/16/2016" into a friendly date format that rails can handle.
I have a calendar in which users can select a from_date and a to_date.. based on those params, my search will then filter results that fit the time periods.
Unfortunately, rails cannot handle the current format its in. Not sure the best way to go about this. I could change the search form's javascript to display the date differently, but I feel this format is most user friendly.
thx!
You can use the standard ruby Date class:
some_date = Date.strptime('01/16/2016', '%m/%d/%Y')
some_date will be an instance of Date, which then you can handle in rails and reformat in any way you want using strftime.
As like taglia said you can use the strptime
Date.strptime('01/16/2016', '%m/%d/%Y')
You can change the calendar date format from dd/mm/yyyy to mm/dd/yyyy, then you can use
require 'date'
date = DateTime.parse("16/01/2016")
=> #<DateTime: 2016-01-16T00:00:00+00:00 ((2457404j,0s,0n),+0s,2299161j)>
date.strftime('%a %b %d %H:%M:%S %Z %Y')
=> "Sat Jan 16 00:00:00 +00:00 2016"
You can use Date instead of DateTime if you want only the date.
Related
In my rails app, I have the following configuration for date formats:
config/initializers/time_formats.rb
Date::DATE_FORMATS[:concise] = "%d/%b/%Y"
Time::DATE_FORMATS[:concise] = "%d/%b/%Y %H:%M %Z"
In my view, if I do:
MODEL.created_at.to_formatted_s(:concise)
... it correctly picks-up the :concise format for the datetime date type, and renders it as follows:
13/Oct/2020 05:00 UTC
Note that the %b is the short Month name - Oct in this case. If I only want to show the date, I would assume that I'd simply use the to_date method to convert the datetime to a date first:
MODEL.created_at.to_date.to_formatted_s(:concise)
This does render a date, but it doesn't pick up the :concise date format properly. It renders:
13/10/2020
Note it's not rendering October as 10, instead of formatting as %b. I've tried adding a :default date type in time_formats.rb but that didn't fix it.
Why is this happening just for the Date type?
(I'm using ruby 2.5.8, Rails 6.)
I'm using Rails. I've stored a count by month in a postgres db as a hash using hstore.
The stored hash is formatted as follows:
{"2017-03-01 00:00:00 UTC"=>"10", "2017-04-01 00:00:00 UTC"=>"3"}
I'm struggling to find a great way to retrieve specific month counts from this hash due to the date format used for the key.
QUESTION
What is the best way to format a string to match the current hash key date format?
For example for March in the Hash the key is "2017-03-01 00:00:00 UTC"
However, a new DateTime for March 1 2017 is formatted as "2017-03-01T00:00:00+00:00"
Or is it best to change the format of how I am storing the hash in the first place?
If you need a timestamp in a specific format, the standard tool to use is DateTime#strftime (all the time-ish classes will have a strftime method and they all behave the same). In your case:
some_datetime.utc.strftime('%Y-%m-%d %H:%M:%S %Z')
And hooking that up to ActiveRecord:
Model.where('your_hstore -> :key', :key => some_datetime.utc.strftime('%Y-%m-%d %H:%M:%S %Z'))
Or:
Model.where('your_hstore -> ?', some_datetime.utc.strftime('%Y-%m-%d %H:%M:%S %Z'))
%Z should be the "Time zone abbreviation name" and for me it produces strings like 'UTC', 'PDT', ... If your strftime (which almost certainly is just a wrapper around the system's libc version of strftime) doesn't produce the strings that you want then you have some options:
Drop the timezone completely if it will always be UTC. Then the keys would look like 2017-03-01 00:00:00 and you'd use '%Y-%m-%d %H:%M:%S' as your strftime format string.
If they keys are actually just dates as they appear to be, then use dates and drop the time-of-day. Then your keys would look like 2017-03-01, you'd use Date instances in Ruby rather than DateTimes, and you'd say some_date.strftime('%Y-%m-%d') or some_date.iso8601 in Ruby to get your hstore keys.
If you are using non-UTC timezones, then convert everything to UTC and go with 1 or 2.
If you don't want any of the above, switch to numeric timezone offsets (2017-05-10 18:05:57 +0000, 2017-05-10 18:06:48 +00:00, ...) and use %z, %:z, or %::z in the strftime format string (see the docs for difference between these three).
These of course require reworking any data you already have in the database but it is best to get the out of the way sooner rather than later.
I have datetime strings that are outputted in the following format:
03/27/2014 07:52:47 PM
I'm using a gem called rufus-scheduler, which takes strings in a YYYY-mm-dd hh-MM-ss #### (#### is timezone offset). Are there any easy ways to convert the first string I had to a string in the format rufus-scheduler likes?
I know that one way I could do it would be to create a method that parsed the string so I could create a new datetime object from it, and then call a strftime in the format rufus likes, but I was wondering if there were any more efficient ways to go about solving my problem.
You can use DateTime::strptime to parse, and DateTime#strftime to format it again.
First require 'date' and then:
2.0.0-p451 :021 > DateTime.strptime("03/27/2014 07:52:47 PM", "%m/%d/%Y %H:%M:%S %p").strftime("%Y-%m-%d %H-%M-%S %z")
=> "2014-03-27 19-52-47 +0000"
Check out Time.strftime
Also, http://www.foragoodstrftime.com/ is an awesome tool for this.
Chronic (https://github.com/mojombo/chronic) is your friend
require 'chronic'
p Chronic.parse('03/27/2014 07:52:47 PM')
I have a form input in my application that accepts dates in the format DD/MM/YYYY eg 02/05/2012 is 2nd May 2012.
What is the best way for me to convert this into a suitable format to be added to the database through ActiveRecord?
Is there a simply way of converting 02/05/2012 to 05/02/2012 before adding to the database?
This is similar to Getting rails to accept European date format (dd/mm/yyyy)
In your model, create a setter method, where "my_date" is your database field.
def my_date=(val)
Date.strptime(val, "%d/%m/%Y") if val.present?
end
For this specific format you can call DateTime.parse:
DateTime.parse("02/05/2012") # => Thu, 02 May 2012 00:00:00 +0000
2 Years later but it's something I came across too, here's my fix.
In your view, use:
<%= l article.created_at, format: :euro %> **make sure to add the l
And then in /config/locales/en.yml add:
en:
time:
formats:
euro: "%d/%m/%Y"
** you can also just add, euro: "%D" to display in the us date format.
Thanks.
I have a birthday field in my database which has a date value as yyyy-mm-dd. I want to display it as being more human friendly. So 2011-11-15 should show up as Tuesday, November 15th, 2011.
The very strange thing is that when i do a #user.birthday in rails console, the value does show up in the format I want. But not on the web.
I am not sure what's going on.
The reason it does not show up in the right format is that Rails in the view does call a to_s if necessary.
You should the Internationalization and Localization of Rails to do that.
So in your example, I18n.l #user.birthday should do the trick. You should check what the default date format for your locale is, this is located at `config/locales/.yml. You may add your format by following the explanation in "How to store custom translations". So by adding
en:
date:
formats:
default: "%A, %B %d,%Y"
this format will be used where ever you call I18n.l on a date.
#user.birthday.strftime "%A, %B %d,%Y"
Try this <model>.created_at.to_date.to_s(:long)