在 Ruby 中解析日期字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11617410/
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
Parse Date string in Ruby
提问by Kevin
I have a String 20120119which represents a date in the format 'YYYYMMDD'.
我有一个字符串20120119,它表示格式为 的日期'YYYYMMDD'。
I want to parse this string into a Ruby object that represents a Date so that I can do some basic date calculation, such as diff against today's date.
我想将此字符串解析为表示日期的 Ruby 对象,以便我可以进行一些基本的日期计算,例如与今天的日期进行比较。
I am using version 1.8.6 (requirement).
我使用的是 1.8.6 版(要求)。
回答by robustus
You could use the Date.strptimemethod provided in Ruby's Standard Library:
您可以使用Date.strptimeRuby 标准库中提供的方法:
require 'date'
string = "20120723"
date = Date.strptime(string,"%Y%m%d")
Alternately, as suggested in the comments, you could use Date.parse, because the heuristics work correctly in this case:
或者,正如评论中所建议的,您可以使用Date.parse,因为在这种情况下启发式可以正常工作:
require 'date'
string = "20120723"
date = Date.parse(string)
Both will raise an ArgumentErrorif the date is not valid:
ArgumentError如果日期无效,两者都会引发:
require 'date'
Date.strptime('2012-March', '%Y-%m')
#=> ArgumentError: invalid date
Date.parse('2012-Foo') # Note that '2012-March' would actually work here
#=> ArgumentError: invalid date
If you also want to represent hours, minutes, and so on, you should look at DateTime. DateTime also provides a parsemethod which works like the parse method on Date. The same goes for strptime.
如果您还想表示小时、分钟等,您应该查看DateTime。DateTime 还提供了一种parse方法,其工作方式类似于 上的 parse 方法Date。也是如此strptime。

