Forum: Ruby on Rails Changing default date format in Rails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dav Y. (Guest)
on 2006-03-14 06:02
(Received via mailing list)
I've spent all day digging through the rails api and postgres-pr on
this, I think it's time to ask the list.

Postgres stores a Date in YYYY-MM-DD format. My users want the dates
in MM/DD/YYYY format.

Sure, I could explicitly convert it on the app level every place where
a date is displayed, but that seemed like a DRY violation.

I thought I'd be clever and simply redefine Date.to_s with

class Date
  def to_s
    strftime('%m/%d/%Y')
  end
end
Craig W. (Guest)
on 2006-03-14 06:11
(Received via mailing list)
On Mon, 2006-03-13 at 20:01 -0800, Dav Y. wrote:
>
> class Date
>   def to_s
>     strftime('%m/%d/%Y')
>   end
> end
----
I don't know the answer but I appreciate the question...that one is on
my todo list so when you do get a resolve on it, please post back to the
list.

Craig
Josh S. (Guest)
on 2006-03-14 10:18
Dav Y. wrote:
> I've spent all day digging through the rails api and postgres-pr on
> this, I think it's time to ask the list.
>
> Postgres stores a Date in YYYY-MM-DD format. My users want the dates
> in MM/DD/YYYY format.
>
> Sure, I could explicitly convert it on the app level every place where
> a date is displayed, but that seemed like a DRY violation.

There's already a nice way to do this. ActiveSupport enhances Date#to_s
to take a format parameter. Fire up script/console and look at the value
of this hash:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS

If you add an entry for :default, that will be used for all to_s
conversions where you don't specify a format. And you can use
some_date.to_s(:db) to output in the format for your database.  If you
want to change or add formats, put something like this in your
environment.rb after the end of the Initializer block:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :default => '%m/%d/%Y',
  :date_time12  => "%m/%d/%Y %I:%M%p",
  :date_time24  => "%m/%d/%Y %H:%M",
)

--josh
http://blog.hasmanythrough.com
Josh S. (Guest)
on 2006-03-14 18:25
Josh S. wrote:
> Dav Y. wrote:
>> I've spent all day digging through the rails api and postgres-pr on
>> this, I think it's time to ask the list.
>>
>> Postgres stores a Date in YYYY-MM-DD format. My users want the dates
>> in MM/DD/YYYY format.
>>
>> Sure, I could explicitly convert it on the app level every place where
>> a date is displayed, but that seemed like a DRY violation.
>
> There's already a nice way to do this. ActiveSupport enhances Date#to_s
> to take a format parameter. Fire up script/console and look at the value
> of this hash:
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS
>
> If you add an entry for :default, that will be used for all to_s
> conversions where you don't specify a format. And you can use
> some_date.to_s(:db) to output in the format for your database.  If you
> want to change or add formats, put something like this in your
> environment.rb after the end of the Initializer block:
>
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
>   :default => '%m/%d/%Y',
>   :date_time12  => "%m/%d/%Y %I:%M%p",
>   :date_time24  => "%m/%d/%Y %H:%M",
> )

Oops, two small corrections. (No more late night postings!)  For a Date,
you want to use this hash:
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS

>And you can use some_date.to_s(:db) to output in the format for your database.

By the above I meant that Rails uses the :db formatter when converting a
date to a string to use in a database query. So if you need to you can
change the :db format and the way dates are formatted for the database
will change automatically.

--josh
http://blog.hasmanythrough.com
Dav Y. (Guest)
on 2006-03-14 21:48
(Received via mailing list)
Argh, Gmail ate over half of my original post so I didn't actually
explain myself.

Josh, thanks for the tip on the CoreExtension stuff. Unfortunately it
doesn't really help.

The problem is that both the DATE_FORMATS thing, and my Date.to_s
overwrite, don't extend deep enough into the rails system. It works
great once you have a model object and are just calling the attribute
reader methods on it, but when you use the ActionView helpers like
text_field or in_place_editor the customized default does come into
play. By digging into the rails code, I found that this is because
these tag helpers end up calling object.attribute_before_type_cast
which simply returns the raw string from the sql results. Let me
illustrate:

script/console
Loading development environment.
>> ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS
=> {:short=>"%e %b", :long=>"%B %e, %Y"}

>> Date.today.to_s
=> "2006-03-14"

>> ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default]='%m/%d/%Y'
=> "%m/%d/%Y"

>> Date.today.to_s
=> "03/14/2006"

(w00t)

>> r = Rebate.find 30
=> #<Rebate:0x2276778 @attributes={"reminder_list"=>"0",
"status"=>"2", "prorated"=>"0", "updated_at"=>nil,
"service_period"=>"14", "employee_id"=>"1", "id"=>"30",
"customer_id"=>"30", "reminder_cancel_date"=>nil, "amount"=>"300.00",
"credit_on"=>"2005-12-17", "service_fee"=>"75.00",
"created_at"=>"2005-12-17 14:35:19"}>

>> r.credit_on.to_s
=> "12/17/2005"

(w00t!)

>> av = ActionView::Base.new
=> #<ActionView::Base:0x25779b8 @assigns_added=nil, @controller=nil,
@base_path=nil, @assigns={}, @logger=nil>

>> av.instance_variable_set("@rebate",r)
=> #<Rebate:0x2276778 @attributes={"reminder_list"=>"0",
"status"=>"2", "prorated"=>"0", "updated_at"=>nil,
"service_period"=>"14", "employee_id"=>"1", "id"=>"30",
"customer_id"=>"30", "reminder_cancel_date"=>nil, "amount"=>"300.00",
"credit_on"=>"2005-12-17", "service_fee"=>"75.00",
"created_at"=>"2005-12-17 14:35:19"}>

>> av.text_field :rebate, 'credit_on'
=> "<input id=\"rebate_credit_on\" name=\"rebate[credit_on]\"
size=\"30\" type=\"text\" value=\"2005-12-17\" />"

(!w00t)

I don't want to use a solution that requires me to give up on some of
the nicer parts of RoR. So this is where I became stuck. I took some
time to dig around in the ConnectionAdapter stuff, but I don't see an
easy way to do what I want through that level either, although to be
honest I found some of the Postgres specific stuff confusing.



On 3/14/06, Josh S. <removed_email_address@domain.invalid> wrote:
> >
> >
> >And you can use some_date.to_s(:db) to output in the format for your database.
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> removed_email_address@domain.invalid
> http://lists.rubyonrails.org/mailman/listinfo/rails
>


--
Dav Y.
http://AkuAku.org/
Ed Howland (Guest)
on 2006-07-31 20:26
(Received via mailing list)
Dan,

Just to solve this particular problem with date formats with
in_place_editor_field, I just augmented my model. Originally, I had a
date of birth field called dob. I did this in the model:

def dob_formatted
   dob.strftime '%m/%d/%Y'
end'

def dob_formatted=(value)
   self.dob = Time.parse(value)
end

Then in the view:

   <%= in_place_editor_field :client, 'dob_formatted' %>

HTH,
Ed
Kevin O. (Guest)
on 2006-08-01 03:50
(Received via mailing list)
On Monday, July 31, 2006, at 11:25 AM, Ed Howland wrote:
>def dob_formatted=(value)
>On 3/14/06, Dav Y. <removed_email_address@domain.invalid> wrote:
>> text_field or in_place_editor the customized default does come into
>> >> Date.today.to_s
>>
>>
>> "customer_id"=>"30", "reminder_cancel_date"=>nil, "amount"=>"300.00",
>> the nicer parts of RoR. So this is where I became stuck. I took some
>> > >> this, I think it's time to ask the list.
>> > > to take a format parameter. Fire up script/console and look at
>> > >
>> > ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS
>> > --josh
>>
>--
>Ed Howland
>http://greenprogrammer.blogspot.com
>_______________________________________________
>Rails mailing list
>removed_email_address@domain.invalid
>http://lists.rubyonrails.org/mailman/listinfo/rails

Be careful changing the default format.  I had an issue lately where
doing this completely hosed MySQL.  Bottom line is that ActiveRecord was
trying to insert dates into the database in the new default format,
instead of the way MySQL was expecting to get it.  It resulted in empty
dates, but no real error.

Twas quite a pain to track down.


_Kevin
www.sciwerks.com
Kris (Guest)
on 2006-08-28 11:40
Kevin O. wrote:
> On Monday, July 31, 2006, at 11:25 AM, Ed Howland wrote:
>>def dob_formatted=(value)
>>On 3/14/06, Dav Y. <removed_email_address@domain.invalid> wrote:
>>> text_field or in_place_editor the customized default does come into
>>> >> Date.today.to_s
>>>
>>>
>>> "customer_id"=>"30", "reminder_cancel_date"=>nil, "amount"=>"300.00",
>>> the nicer parts of RoR. So this is where I became stuck. I took some
>>> > >> this, I think it's time to ask the list.
>>> > > to take a format parameter. Fire up script/console and look at
>>> > >
>>> > ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS
>>> > --josh
>>>
>>--
>>Ed Howland
>>http://greenprogrammer.blogspot.com
>>_______________________________________________
>>Rails mailing list
>>removed_email_address@domain.invalid
>>http://lists.rubyonrails.org/mailman/listinfo/rails
>
> Be careful changing the default format.  I had an issue lately where
> doing this completely hosed MySQL.  Bottom line is that ActiveRecord was
> trying to insert dates into the database in the new default format,
> instead of the way MySQL was expecting to get it.  It resulted in empty
> dates, but no real error.
>
> Twas quite a pain to track down.
>
>
> _Kevin
> www.sciwerks.com


Did you ever figure out how to fix this? I have the same problem,
changing the default date format effects the way it is passed to mysql.
I would think that the rails team could fix this somehow no?
Conner (Guest)
on 2006-09-02 23:02
I hope this is relevant, I'm just starting out on Ruby, and with Rails,
and I ran into trouble with MySQL dates. Here's how I got what I wanted:

  # This method takes in a MySQL formatted date (YYYY-MM-DD)
  # and returns a date formatted as (M/DD)

  def format_date(date)
         year, month, day = date.split(/-/) # splits date into 3
variables
         month = month.sub(/^0/,'') # Strips leading '0's from the month
         month + "/" + day # concatenates and returns date
  end


I wasn't sure how to get/use Date objects so I restricted myself to the
String class.

I put this method in my helper file.
_Kevin (Guest)
on 2006-09-04 16:43
(Received via mailing list)
Kris wrote:
> >>> > >> this, I think it's time to ask the list.
> >>removed_email_address@domain.invalid
> >
> Posted via http://www.ruby-forum.com/.
Not yet.  That's on the back burner for the moment.  I've just been
using the default output for now and specifically changing it when
necessary.

I think the fix for this is to define a default :db date format and
modify the appropriate AR code to use that format when writing to the
DB.  That way you could change the default print format without
affecting the DB writes.  I think I first encountered this while the
Trac was down, so I'll go submit a ticket on this (if there isn't one
already).

_Kevin
Stuart R. (Guest)
on 2007-03-03 07:40
Kris wrote:
>>>Rails mailing list
>>>removed_email_address@domain.invalid
>>>http://lists.rubyonrails.org/mailman/listinfo/rails
>>
>> Be careful changing the default format.  I had an issue lately where
>> doing this completely hosed MySQL.  Bottom line is that ActiveRecord was
>> trying to insert dates into the database in the new default format,
>> instead of the way MySQL was expecting to get it.  It resulted in empty
>> dates, but no real error.
>>
>> Twas quite a pain to track down.
>>
>>
>> _Kevin
>> www.sciwerks.com
>
>
> Did you ever figure out how to fix this? I have the same problem,
> changing the default date format effects the way it is passed to mysql.
> I would think that the rails team could fix this somehow no?

The problem seems to be solved in the post 1.2.1 Edge Rails revison
6270, March 2007. See TRAC ticket http://dev.rubyonrails.org/ticket/7411
(alternatively 1.2.1 users could patch the quote method in
lib/active_record/connection_adapters/abstract/quoting.rb).

I've written a howto along with a date validator, date_field helper and
calendar control to address the whole date display/input/validation
question at http://www.methods.co.nz/rails_date_kit/rails_date_kit.html

Cheers, Staurt
Miquel H. (Guest)
on 2007-06-25 14:43
Stuart R. wrote:

>> Did you ever figure out how to fix this? I have the same problem,
>> changing the default date format effects the way it is passed to mysql.
>> I would think that the rails team could fix this somehow no?
>
> The problem seems to be solved in the post 1.2.1 Edge Rails revison
> 6270, March 2007. See TRAC ticket http://dev.rubyonrails.org/ticket/7411
> (alternatively 1.2.1 users could patch the quote method in
> lib/active_record/connection_adapters/abstract/quoting.rb).
>
> I've written a howto along with a date validator, date_field helper and
> calendar control to address the whole date display/input/validation
> question at http://www.methods.co.nz/rails_date_kit/rails_date_kit.html
>
> Cheers, Staurt

Following this issue and guided by the Stuart's howto I have written a
post solving this issue in a different way. Besides, time formatting is
also covered.

The post can be found here:
http://blog.nominet.org.uk/tech/2007/06/14/date-an...

Cheers
Miquel
Dave M. (Guest)
on 2007-08-01 23:13
Hi Staurt,

I like your calendar but got into a weird problem where the calendar
overlaps with a drop down select underneath it. I tried to fix it using
the z-index in the css but not lock. It only overlaps with the drop down
control and not with others like text box, text area, buttons, labels
etc.

Any thoughts?

i_programmer
Rick O. (Guest)
on 2007-08-01 23:19
(Received via mailing list)
On 8/1/07, Dave M. <removed_email_address@domain.invalid> wrote:
>
> Hi Staurt,
>
> I like your calendar but got into a weird problem where the calendar
> overlaps with a drop down select underneath it. I tried to fix it using
> the z-index in the css but not lock. It only overlaps with the drop down
> control and not with others like text box, text area, buttons, labels
> etc.
>
> Any thoughts?

Windows?
http://www.devguru.com/features/tutorials/ComboCon...

--
Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com
Chris G. (Guest)
on 2007-08-30 12:38
Josh S. wrote:

> There's already a nice way to do this. ActiveSupport enhances Date#to_s
> to take a format parameter. Fire up script/console and look at the value
> of this hash:
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS
>
> If you add an entry for :default, that will be used for all to_s
> conversions where you don't specify a format. And you can use
> some_date.to_s(:db) to output in the format for your database.  If you
> want to change or add formats, put something like this in your
> environment.rb after the end of the Initializer block:
>
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
>   :default => '%m/%d/%Y',
>   :date_time12  => "%m/%d/%Y %I:%M%p",
>   :date_time24  => "%m/%d/%Y %H:%M",
> )
>
> --josh
> http://blog.hasmanythrough.com

How can I tell to_xml to format a date according to one of these
predefined formats? Thanks,

Chris.
Chris G. (Guest)
on 2007-08-30 16:36
Chris Gers32 wrote:

> How can I tell to_xml to format a date according to one of these
> predefined formats? Thanks,
>
> Chris.

I got a reply from Railsfrance; I just redefine XML_FORMATTING locally,
like this:


    old_proc = Hash::XML_FORMATTING['datetime']
    Hash::XML_FORMATTING['datetime'] = Proc.new { |datetime|
datetime.to_s(:rfc822) }

    MY CODE THAT CALLS to_xml GOES HERE

    Hash::XML_FORMATTING['datetime'] = old_proc

Chris.
Ben C. (Guest)
on 2008-03-04 07:19
Dave M. wrote:
> Hi Staurt,
>
> I like your calendar but got into a weird problem where the calendar
> overlaps with a drop down select underneath it. I tried to fix it using
> the z-index in the css but not lock. It only overlaps with the drop down
> control and not with others like text box, text area, buttons, labels
> etc.
>
> Any thoughts?
>
> i_programmer

This is an issue with Internet Explorer. The easiest way to fix this
problem is by wrapping the div you want to be above the select box in an
iframe. Here is a simple jquery plugin that demonstrates the technique.
You should be able to easily port this to other JavaScript libraries to
solve the issue.

http://brandonaaron.net/jquery/plugins/bgiframe/jq...

Hope this helps!
Luca B. (Guest)
on 2009-12-15 18:07
Hello,
I found that the easiest way for me is using the built-in
localization/i18n support.

If the application is localized, you could include the appropriate
format in the localization file, and then you could use the "localize"
helper:
<%=localize object.time_attribute, :format => :custom_or_edited_format
%>.

If the application is not localized, it is after all even easier/faster
using the same technique.

Hope this helps.


Dav Y. wrote:
> I've spent all day digging through the rails api and postgres-pr on
> this, I think it's time to ask the list.
>
> Postgres stores a Date in YYYY-MM-DD format. My users want the dates
> in MM/DD/YYYY format.
>
> Sure, I could explicitly convert it on the app level every place where
> a date is displayed, but that seemed like a DRY violation.
>
> I thought I'd be clever and simply redefine Date.to_s with
>
> class Date
>   def to_s
>     strftime('%m/%d/%Y')
>   end
> end
Sean C. (Guest)
on 2010-05-18 23:40
In Rails3 you can run:

Date::DATE_FORMATS[:default] = "%m/%d/%Y"

skipping the ActiveSupport::CoreExtensions::...

see your installation of active support, eg:

activesupport-3.0.0.beta3/lib/active_support/core_ext/conversions.rb for
more info.

Josh S. wrote:
> Dav Y. wrote:
>> I've spent all day digging through the rails api and postgres-pr on
>> this, I think it's time to ask the list.
>>
>> Postgres stores a Date in YYYY-MM-DD format. My users want the dates
>> in MM/DD/YYYY format.
>>
>> Sure, I could explicitly convert it on the app level every place where
>> a date is displayed, but that seemed like a DRY violation.
>
> There's already a nice way to do this. ActiveSupport enhances Date#to_s
> to take a format parameter. Fire up script/console and look at the value
> of this hash:
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS
>
> If you add an entry for :default, that will be used for all to_s
> conversions where you don't specify a format. And you can use
> some_date.to_s(:db) to output in the format for your database.  If you
> want to change or add formats, put something like this in your
> environment.rb after the end of the Initializer block:
>
> ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
>   :default => '%m/%d/%Y',
>   :date_time12  => "%m/%d/%Y %I:%M%p",
>   :date_time24  => "%m/%d/%Y %H:%M",
> )
>
> --josh
> http://blog.hasmanythrough.com
Krishna C. (Guest)
on 2011-02-24 20:19
When i use,

Date::DATE_FORMATS[:default] = "%m/%d/%Y"

in environment.rb file or any .rb file in config/initializers, works
fine Rails 3.0.1, but the same doesn't work with Rails 3.0.4.

Please let me know if there is some other way to define default date
formats at application level or if you need any other information.

Thanks
Chaitanya


Sean Corbett wrote in post #913239:
> In Rails3 you can run:
>
> Date::DATE_FORMATS[:default] = "%m/%d/%Y"
>
> skipping the ActiveSupport::CoreExtensions::...
>
> see your installation of active support, eg:
>
> activesupport-3.0.0.beta3/lib/active_support/core_ext/conversions.rb for
> more info.
>
Valentine B. (Guest)
on 2011-03-28 17:59
Use Rails I18n for this.

In config/locales/en.yml:

en:
  date:
    formats:
      default: "%m/%d/%Y"


In views:

<%= l some_model.date_field %>
Petr M. (Guest)
on 2011-08-16 12:45
And what about helpers?
I would like to let users to enter date in the text field (faster then
3x select), so value for some_object.date_attribute
should in f.text_field(:date_attribute)
be "21.7.2011" (not "2011-07-21").

I am using virtual atributes for now:

def date_attribut_to_s
   if self.date_attribute.kind_of?(Date)
    return self.date_attribute.strftime("%d.%m.%Y")
   else
     return self.date_attribute
   end
end

def date_attribut_to_s=(maybe_date)
    date=nil

    if maybe_date.blank?
      self.date_attribute=nil
    elsif mybe_date.kind_of?(Date)
      self.date_attribute=maybe_date
    else
      begin
        #some more complex date parsing required?
        date = Date.strptime(maybe_date, "%d.%m.%Y")
      rescue
        self.errors.add(:date_attribute,"Invalid date")
      end
      self.date_attribute = date unless date.blank?
   end
end

and use it in view as  f.text_field(:date_attribute_to_s) .

Foton





Valentine B. wrote in post #989611:
> Use Rails I18n for this.
>
> In config/locales/en.yml:
>
> en:
>   date:
>     formats:
>       default: "%m/%d/%Y"
>
>
> In views:
>
> <%= l some_model.date_field %>
Colin L. (Guest)
on 2011-08-16 12:52
(Received via mailing list)
On 16 August 2011 09:45, Petr M. <removed_email_address@domain.invalid> wrote:
>  return self.date_attribute.strftime("%d.%m.%Y")
>  elsif mybe_date.kind_of?(Date)
> end
>
> and use it in view as f.text_field(:date_attribute_to_s) .

So what is the question?

Colin
This topic is locked and can not be replied to.