开发者

Ruby - convert string to date

I have a string like "2011-06-02T23:59:59+05:30".

I wan开发者_Python百科t to convert it to date format and need to parse only the date, "2011-06-02".


For Ruby 1.9.2:

require 'date'    # If not already required. If in Rails then you don't need this line).
puts DateTime.parse("2011-06-02T23:59:59+05:30").to_date.to_s


require 'date'
d = Date.parse("2011-06-02T23:59:59+05:30")
d.strftime("%F")


Simplies way is

require 'date'
date = "2011-06-02T23:59:59+05:30".gsub(/T.*/, '')
DateTime.parse(date)


Time.parse() should allow you to parse the whole date time. Then you can use time.strftime( string ) to format that as just a date in a string.

date = Time.parse("2011-06-02T23:59:59+05:30")
date_string = time.strftime("%y-%m-%d")
of
date_string = time.strftime("%F")

(see Ruby Doc for Time for more output string formats) The above should work if you want a string; if you want a date object to handle then the ruby Date class can help you handle it but I belive that everything still needs to be done with Time objects; see Ruby Doc for Date for details of the Date class.

Hope that helps, let me know if I have headed off in the wrong direction with my answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜