Topic: strptime issue

Hi all.

I am using DateTime.strptime to get a DateTime object from a date formatted as d/m/y
using the following code

    fmt = '%d/%m/%y'
    begin
      from = DateTime.strptime(params[:from]).yday
     rescue ArgumentError => arg_exc
    ...


where params[:from] is like 23/01/2007 but I get an ArgumentError exception with the message
"3 elements of civil date are necessary".
Anyone know what is the correct use of this library?

Thanks

Re: strptime issue

I think you forgot the fmt parameter in the call to strptime:

from = DateTime.strptime(params[:from], fmt).yday

You can also use Date class for this if you aren't interested in the time part.

Re: strptime issue

I have just tried with fmt but the result is the same


  Parameters: {"from"=>"10/01/2007", 

fmt = '%d/%m/%y'
from = DateTime.strptime(params[:from], fmt).yday

3 elements of civil date are necessary

Re: strptime issue

Can you try just plugging in a quoted date into the strptime arg 1 and see if that works as you expect.  If it does then it means that the from param is not as you expect.

Regards,
Richard

PlanetGPS.net
RogueWaveMarine.com
===================================

Re: strptime issue

Meanwhile, has anybody a solution for this problem?
I've tried willirls suggestion but even something like this

Date.strptime("01/02/2007", '%d.%m.%Y')

leads to an ArgumentError "3 elements of civil date are necessary".

I did not expect that localizing and especially localizing dates is such a complicated thing in RoR. sad

Re: strptime issue

Almost there...

The format is the format of the date that you are parsing so for the input date of "01/02/2007" you would need to do this:

Date.strptime("01/02/2007", '%d/%m/%Y')

Re: strptime issue

Oh, I see. So I was on a completly wrong trace while I thought the second parameter would define how the date format should look like AFTER parsing. Sorry, my fault.

Of course this leads to the next question HOW is it possible to get a Date object in the desired format? Or a bit simplified how can I convert a string to date without modifying the format?

I tried something like

d.strftime('%d.%m.%Y').to_date # d is "2007-01-30" e.g.

but then I receive an error

You have a nil object when you didn't expect it!
The error occurred while evaluating nil./

What am I doing wrong?

Re: strptime issue

This works for me:

require 'date'
now = DateTime.now
n = now.strftime('%d.%m.%Y')
p n

Re: strptime issue

Hm ... I tried your code but I always receive a nil object. Maybe a stupid question but what is the meaning of the last line? (Did I mention that I am a newbie to RoR? smile)

Last edited by BigTitus (2007-02-22 11:43:37)

Re: strptime issue

Sorry the "p n" just prints the value of n.

I am testing this code in irb.  (interactive ruby)  if you are on a unix or linux box just type in "irb" at the command prompt.  Then you can enter ruby code and see what happens.

It sounds like you have some other problem than with the date stuff.  Can you show all the code you are using?  Include the traceback as well.

Re: strptime issue

willirl wrote:

Sorry the "p n" just prints the value of n.

Yes, after a second try I found it in the documentation, sorry. #roll#

According to this thread text_field datetime format I try to override the standard accessors of a model.

# external lib file

class ActiveRecord::Base
     
  def self.formatted_date_accessor(*names)
    names.each do |name|
      define_method("#{name}") do ||
        self[name].strftime('%d.%m.%Y')
      end

      # ...

    end
  end
end


# this line is in the model

formatted_date_accessor :date # "date" is a date column, db is mysql


The views are standard scaffold views. In the list view everything works fine but in the edit view I get an error due to date_select is expecting a Date object:

"undefined method `day' for "01.01.2005":String"

That's the main problem. big_smile

Re: strptime issue

Why are you overriding the standard accessor? The helper methods like date_select expect a Date object, not String. You should give the formatted date accessor a different name so it doesn't override the main accessor (which returns the Date object).

class ActiveRecord::Base
     
  def self.formatted_date_accessor(*names)
    names.each do |name|
      define_method("formatted_#{name}") do
        self[name].strftime('%d.%m.%Y')
      end
      #...
    end
  end
end

If you are wanting the date_select method to put the menus in a different order you can do that with the ":order" option:

<%= date_select :my_model, :date, :order => [:day, :month, :year] %>

Railscasts - Free Ruby on Rails Screencasts

Re: strptime issue

Thats definitely the better way but then this won't work anymore:

<% for column in Voucher.content_columns %>
  <td><%=h voucher.send(column.name) %></td>
<% end %>

As long as there is only one date column or the table has just a few columns one could think about a manual solution but if there is a bigger table with umpteen columns and maybe a lot of date columns it would be comfortable to use the code above AND have a proper localization, too.

So, that's why I tried to override the standard accessors. But this doen't seem to be a good idea?!

Re: strptime issue

I recommend always going with the manual solution. Never loop through the columns as scaffolding does. Sooner or later you'll want more control as to what columns are displayed, how they are displayed, and the order they are displayed in.

Alternatively, you can add a to_s to the Date class to return it in the format you wish. This feels hackish to me, but you might want to consider it.

class Date
  def to_s
    strftime('%d.%m.%Y')
  end
end

Actually, the to_s method in Date accepts a parameter which determines how it is formatted. You should look into that so the above code works with that parameter.

Edit
Actually, try this instead:

# in environment.rb
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%d.%m.%Y')

Untested.

Last edited by ryanb (2007-02-22 12:58:12)

Railscasts - Free Ruby on Rails Screencasts

Re: strptime issue

Well, I trust in your experience so I will overcome my laziness and choose the manual variant. wink

Thanks for your help again!!

Re: strptime issue

ryanb wrote:

# in environment.rb
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%d.%m.%Y')

Untested.

That was one of my first tries (within the LocalizationSimplified plugin) but this even leads to problems. (See also Ticket #6019 ([PATCH] Changing default date format ...)

Re: strptime issue

Didn't realize there were issues with this. That's good to know, thanks! smile

Railscasts - Free Ruby on Rails Screencasts