Pergunta

I am trying to convert a datetime that is returning back from a soap service which looks like this: "2011-09-30T11:25:56-05:00".

I want to parse it to this format "2011-09-30 11:25:56"

When I hard code the datestring in my ruby code, it works:

def parse_date(datestring)
    formattedDateTime = DateTime.strptime("2011-09-30T11:25:56-05:00", "%Y-%m-%dT%I:%M:%S%z")
    dt = formattedDateTime.strftime("%Y-%m-%d %H:%M:%S")

    return dt
end

This example works when I hard code the datestring in. However, the below example will not work. The datestring that it is using is "2011-09-30T11:25:56-05:00", which is the exact same as I am hardcoding in the above example.

def parse_date(datestring)
    formattedDateTime = DateTime.strptime(datestring, "%Y-%m-%dT%I:%M:%S%z")
    dt = formattedDateTime.strftime("%Y-%m-%d %H:%M:%S")

    return dt
end

This way it throws this error: [01:29:06 PM 2011-10-09] SourceAdapter raised query exception: private method `sub!' called for #

Can anyone please let me know what is going on?

Foi útil?

Solução 2

I figured out the issue. I had to call to_s because the date that I was trying to parse was really not a string.

def parse_date(dateobject)

    tempdatestring = dateobject.to_s

    formattedDateTime = DateTime.strptime(tempdatestring, "%Y-%m-%dT%H:%M:%S%z")
    dt = formattedDateTime.strftime("%Y-%m-%d %H:%M:%S")

    return dt
end

Outras dicas

I can't replicate this problem. What is the scope surrounding this method call and definition?

Without more information, it's nearly impossible to tell what your problem is, but see guess below.

$ irb
ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > def parse_date(datestring)
ruby-1.9.2-p180 :003?>   formattedDateTime = DateTime.strptime("2011-09-30T11:25:56-05:00", "%Y-%m-%dT%I:%M:%S%z")
ruby-1.9.2-p180 :004?>   dt = formattedDateTime.strftime("%Y-%m-%d %H:%M:%S")
ruby-1.9.2-p180 :005?>   
ruby-1.9.2-p180 :006 >   return dt
ruby-1.9.2-p180 :007?> end
 => nil 

ruby-1.9.2-p180 :008 > parse_date nil
 => "2011-09-30 11:25:56" 

ruby-1.9.2-p180 :009 > def parse_date(datestring)
ruby-1.9.2-p180 :010?>   formattedDateTime = DateTime.strptime(datestring, "%Y-%m-%dT%I:%M:%S%z")
ruby-1.9.2-p180 :011?>   dt = formattedDateTime.strftime("%Y-%m-%d %H:%M:%S")
ruby-1.9.2-p180 :012?>   
ruby-1.9.2-p180 :013 >   return dt
ruby-1.9.2-p180 :014?> end
 => nil 

ruby-1.9.2-p180 :015 > parse_date "2011-09-30T11:25:56-05:00"
 => "2011-09-30 11:25:56" 

ruby-1.9.2-p180 :016 > 

I would venture a guess, though. Try this..

def parse_date (datestring)
  DateTime.parse(datestring).strftime("%Y-%m-%d %H:%M:%S")
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top