Ruby 解析日期字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21391953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:22:27  来源:igfitidea点击:

Ruby parse date string

rubydatedate-formatdate-parsing

提问by user1810502

I need to parse a date string mentioned below to std date format.

我需要将下面提到的日期字符串解析为标准日期格式。

Is there a built in function in ruby that would parse something like,

ruby 中是否有内置函数可以解析类似的东西,

December 09, 2011 to 2011-12-09

2011年12月9日至2011-12-09

回答by knut

Date.parseis already mentioned.

Date.parse已经提到了。

I prefer Date.strptime. This methods is a reverse strftime.

我更喜欢Date.strptime。此方法是反向 strftime

Date.parseis a (maybe good) guess, with Date.strptimeyou can parse each date, when you know which format you expect.

Date.parse是一个(可能很好)的猜测Date.strptime,当您知道您期望哪种格式时,您可以解析每个日期。

Example:

例子:

require 'date'
puts  Date.strptime('December 09, 2011', '%B %d, %Y')

Or if you have another format where Date.parsefails:

或者,如果您有另一种格式Date.parse失败

require 'date'
puts Date.strptime("28-May-10", "%d-%b-%y") #2010-05-28

回答by Arup Rakshit

Do as below using Date::parse:

使用以下方法执行以下操作Date::parse

require 'date'
Date.parse('December 09, 2011').to_s # => "2011-12-09"