ruby Time Date DateTime

来自《the ruby way (the second edition)》 

Time、Date、Datetime 的转换和区别:

Ruby有三个处理日期和时间的基本类:Time、Date、Datetime,对它们的描述如下:

1.Time类主要是对底层的C库时间函数的封装。这些函数通常基于UNIX纪元,因此不能表示1970年前的时间。

2.Date类是为了弥补Time类的缺点创建的,它能轻松地处理较早的时间,如达芬奇的生日(1452年4月15日),还能够智能处理历法改革的日期。但它也有缺点,如不能处理达芬奇的出生时间,它只能处理日期。

3.DateTime类继承了Date,旨在比上述两者都好。它可以像Date那样表示日期,也可以像Time那样表示时间。它通常是表示日期——时间值的“正确”方式。

7.19. Interconverting Between Time, Date, and DateTime

Ruby has three basic classes dealing with dates and times: Time, Date, and DateTime. The following is a description of each:

  • The Time class is mostly a wrapper for the underlying time functions in the C library. These are typically based on the UNIX epoch and thus cannot represent times before 1970.

  • The Date class was created to address this shortcoming of the Time class. It can easily deal with older dates such as Leonardo da Vinci's birthday (April 15, 1452), and it is intelligent about the dates of calendar reform. But it has its own shortcoming; it can't deal with the time of day that Leonardo was born. It deals strictly with dates.

  • The DateTime class inherits from Date and tries to be the best of both worlds. It can represent dates as well as Date can, and times as well as Time can. This is often the "right" way to represent a date-time value.

    But don't be fooled into thinking that a DateTime is just a Date with an embedded Time. There are, in fact, several methods missing from DateTime, such as usec, dst?, and others.

   So we have these three classes. Unfortunately there is no good standard way to convert between them. As Ruby continues to change, some of these details will be ironed out. For now, these methods in Listing 7.2 will suffice. Thanks to Kirk Haines for providing them.

Listing 7.2. Interconverting Between Date and Time Classes

 

class Time
  def to_date
    
Date.new(yearmonthday)
  rescue NameError
    nil
  
end

  def to_datetime
    DateTime.new(
yearmonthdayhour, min, sec)
  rescue NameError
    nil
  
end
end

class DateTime
  def to_time
    Time.local(
year,month,day,hour,min,sec)
  
end
end

class Date
  def to_time
    Time.local(
year,month,day)
  
end
end

 

Any exceptions will be propagated except NameError. Why do we check for this one? Because it is conceivable that the program doesn't do a require of the date library (remember that Date and DateTime are part of this standard library, not part of the core). In such a case, to_datetime and to_date will both return nil.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值