How can I convert "Sat Nov 06 05:48:16 +0000 2010" to '11-06-2010' in Ruby?
How can I convert "Sat Nov 06 05:48:16 +0000 2010"
to '11-06-2010开发者_运维问答'
in Ruby? I've tried
Date.strptime("Sat Nov 06 05:48:16 +0000 2010", '%m-%d-%Y')
but I get this error:
ArgumentError (invalid date):
/Users/ben/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/date.rb:1688:in `new_by_frags'
/Users/ben/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/date.rb:1713:in `strptime'
I'm using ruby 1.9.2p0 (2010-08-18 revision 29036).
What am I doing wrong? Thank for reading.
By my reading of the documentation, your usage of strptime
may be wrong. It seems like the second argument describes the format of the first argument, resulting in a very strict parse of the first argument.
So you can write in explicitly the format of your first argument into the second, and you should be okay.
A far easier solution might just be to use Date.new
. Then, Date.strftime
should give you exactly what you're looking for.
irb(main):001:0> require "date"
=> true
irb(main):002:0> Date.new("Sat Nov 06 05:48:16 +0000 2010").strftime('%m-%d-%Y')
=> "11-06-2010"
require 'time'
Time.parse("Sat Nov 06 05:48:16 +0000 2010").strftime('%m-%d-%Y') # => "11-05-2010"
精彩评论