我有一个字符串20120119
,它表示一个日期,格式为'YYYYMMDD'
。
我想将这个字符串解析为Ruby对象,以表示日期,以便进行一些基本的日期计算,例如与今天的日期相差多少天。
我使用的是1.8.6版本(要求)。
Date.strptime
方法:require 'date'
string = "20120723"
date = Date.strptime(string,"%Y%m%d")
另外,正如评论中所建议的,您可以使用Date.parse
,因为在这种情况下启发式方法可以正确地工作:
require 'date'
string = "20120723"
date = Date.parse(string)
如果日期无效,两者都会抛出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
如果您想表示小时、分钟等,您应该查看DateTime。DateTime还提供了一个parse
方法,它的用法类似于Date
上的解析方法。对于strptime
也是如此。
Date.parse
并不起到验证器的作用(这也是为什么它会抛出一个无意义的 ArgumentError 而不是更有意义的错误信息)。如果你想要验证时间字符串,你可能需要看一些专门用于此目的的 gem,例如 Timeliness。 - robustusDateTime.parse("20060224")
它会返回Fri, 24 Feb 2006 00:00:00 +0000
,但我需要它在特定的时区,比如东部时区。 - Zack HerbertDateTime.parse('20060224').in_time_zone('EST')
- robustus