Parse string into date in rails without view helper - ruby-on-rails

i am converting string into date in my rails application model before saving it into database, how to achieve this using without
strptime
because strptime purpose is to format and used for views and helpers .
string format:
"04-28-2015"(mm-dd-yy)
model:
def rent_commencement_date=(value)
self[:rent_commencement_date] = Date.strptime(value, "%m-%d-%Y").to_s(:db)
end

You can use to_date to convert string into date.
Eg: "01-01-2015".to_date

use it. i think this is helpful for you
date = DateTime.now
puts date.to_date.to_s
Or
"2011-05-19 10:30:14".to_time

Used american_date gem, it automatically coverts american date format into ISO format. no need to use setter to format the date in model.
gem 'american_date'

Related

Parsing string "10:00AM" to DateTime Type?

I'm reading strings off of html but want to store them in a database as a DateTime field type. What is a simple way to do this while correctly preserving AM/PM data?
Thanks!
Your access layer for the database should support the Ruby DateTime type, hence you can parse it as follows:
require 'date'
DateTime.parse("10:00AM")
# => #<DateTime: 2013-08-11T10:00:00+00:00 ((2456516j,36000s,0n),+0s,2299161j)>
The whole meridiem notation (AM/PM) is at the presentation level. Your database will store it in its DateTime structure and everytime your retrieve it back into Rails, you can get your presentation by using strftime
your_date.strftime("%I:%M%p")
=> "10:00AM"

Change default date format to %Y%m%d%H%M%S

I'm using rails 3 and I want to change the default date format of created_at and updated_at date when I save them into the db.
Default date format is %Y-%m-%d %H:%M:%S, but
I would like it to be %Y%m%d%H%M%S
Where should I change the format? I'm trying to create a time_formats.rb in the initializer folder.
Here is content:
class TimeFormats
Time::DATE_FORMATS[:db] = "%Y%m%d%H%M%S"
Time::DATE_FORMATS[:default] = "%Y%m%d%H%M%S"
end
This does not work. Is there someone who can help me? Thank you.
The time and date formats that you define in the initializers apply only when converting them to strings in Ruby. The formats you've defined would be used like Time.now.to_s(:default).
I don't recommend (nor am I aware of a way how) to change how dates are stored in the database. You should let the database store them as it does by default, then change how they are formatted in the views using .to_s(:format) as defined in the initializers.
Normally the database stores the timestamps as a specific timedate datatype rather than a formatted string. If you just want default timestamp printing style to be different, you might try overriding the created_at and updated_at methods:
def updated_at
super.strftime("%Y%m%d%H%M%S")
end

How to display the current date in "mm/dd/yyyy" format in Rails

In my view I want to display the current date in "mm/dd/yyyy" format.
<%= Time.now.strftime("%m/%d/%Y") %>
You could simply do (substitute in Time for DateTime if using straight Ruby -- i.e. no Rails):
DateTime.now.strftime('%m/%d/%Y')
If you're using that format a lot, you might want to create a date_time_formats initializer in your RAILS_ROOT/config/initializers folder (assuming Rails 2), something like this:
# File: date_time_formats.rb
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:human => "%m/%d/%Y"
)
Which will then let you use the more friendly version of DateTime.now.to_s(:human) in your code.
I think you can use .strftime:
t = Time.now()
t.strftime("The date is %m/%d/%y")
This should give "The date is 09/09/10". See here for a great list of the format codes for .strftime.
If you don't need the full year you could try
Time.now.strftime('%D')

Ruby: How do you convert a time or date to a friendly url string?

For instance, if I have a Time.now, how would I convert that to a friendly url string?
Time.now.some_method_here => some_url_friendly_string_here
I believe there is a built-in Ruby method to do so, but I can't seem to locate it on Google. Any ideas?
As you're using Rails (as indicated by your tag), you can use .to_s:
Time.now.to_s
You can specify a time format to the method, which will format the string differently, such as Time.now.to_s(:db). Please see this link for the default date formats. If you don't specify a format, it'll use the same as strftime.
The next part of that page also describes how to add your own time formats, which is very simple:
# Initializer
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
# Any code
Time.now.to_s(:month_and_year) # => September 2010
Everything in ruby is open and extensible
class Time
def to_url_string
self.strftime("%H:%M:%s")
end
end
You can use the strftime method. It's a bit cryptic, but if you look at the docs, you can pick out the year, month, day, etc.
For example, Time.now.strftime("%H:%M:%s") will give the time in hours, minutes and seconds.
You might consider using the xmlschema method which will return a date/time in the format:
CCYY-MM-DDThh:mm:ssTZD
or
CCYY-MM-DDThh:mm:ss.sssTZD
depending on the value of the fraction_digits argument.
This would give you a time like:
2010-09-15T20:31:15+05:00
for example.
See the docs for more info and a link to the code.

ActiveRecord date format

I've run into a spot of bother with date formats in our Rails application.
I have a date field in our view which I want to be formatted as dd/mm/yy. This is how the user will expect to enter their dates, and the datepicker control uses this format.
However, Active Record seems to be expecting mm/dd/yy.
If I enter 01/03/2010, this gets put in as 03 January 2010.
If I enter 25/03/2010, this gets put in a null.
How do I get ActiveRecord to expect Her Majesties date format?
Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy or dd-mm-yy or yyyy-mm-dd or yyyy/mm/dd. You could monkey-patch DateTime.parse, but I would rather move this issue to the View of your application.
I always recommend to use yyyy-mm-dd [hh:mm:ss] as a string representation for a date. Check the documentation of your DatePicker if it supports multiple date-formats.
The jQuery date-picker for example has this covered with dateFormat (for the data that is sent to the server, set this to yyyy-mm-dd) as well as altFormat (for the input the user sees, set this to dd/mm/yyyy).
Add a file called rails_defaults.rb to config\initializers directory; with following lines:
Date::DATE_FORMATS[:default] = '%d/%m/%Y'
Time::DATE_FORMATS[:default]= '%d/%m/%Y %H:%M:%S'
Restart the server and you are good to go.
class Date
class << self
def _parse_with_us_format(date, *args)
if date =~ %r{^(\d+)/(\d+)/(\d+)$}
_parse_without_us_format("#{$3.length == 2 ? "20#{$3}" : $3}-#{$1}-#{$2}", *args)
else
_parse_without_us_format(date, *args)
end
end
alias_method_chain :_parse, :us_format
end
end

Resources