Ruby中DateTime和Time之间有什么区别? [英] What's the difference between DateTime and Time in Ruby?

查看:178
本文介绍了Ruby中DateTime和Time之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么因素会导致我选择一个或另一个?

And what factors would cause me to choose one or the other?

推荐答案

较新版本的Ruby(2.0+)两班之间并没有真正的差异。有些图书馆出于历史原因会使用一个或另一个图书馆,但新的代码不一定需要关心。选择一个以保持一致性可能是最好的,所以尝试并与您的图书馆期望的网格。例如,ActiveRecord喜欢DateTime。

Newer versions of Ruby (2.0+) do not really have significant differences between the two classes. Some libraries will use one or the other for historical reasons, but new code does not necessarily need to be concerned. Picking one for consistency is probably best, so try and mesh with what your libraries expect. For example, ActiveRecord prefers DateTime.

在Ruby 1.9之前的版本和许多系统上,时间表示为描述自1月1日以来的秒数的32位有符号值,1970 UTC,一个围绕POSIX标准 time_t 值的薄包装,并且是有界的:

In versions prior to Ruby 1.9 and on many systems Time is represented as a 32-bit signed value describing the number of seconds since January 1, 1970 UTC, a thin wrapper around a POSIX-standard time_t value, and is bounded:

Time.at(0x7FFFFFFF)
# => Mon Jan 18 22:14:07 -0500 2038
Time.at(-0x7FFFFFFF)
# => Fri Dec 13 15:45:53 -0500 1901

较新版本的Ruby能够处理更大的值而不会产生错误。

Newer versions of Ruby are able to handle larger values without producing errors.

DateTime是一种基于日历的方法,其中年,月,日,时,分和秒分别存储。这是一个Ruby on Rails构造,用作围绕SQL标准DATETIME字段的包装器。这些包含任意日期,并且可以表示几乎任何时间点,因为表达式的范围通常非常大。

DateTime is a calendar-based approach where the year, month, day, hour, minute and second are stored individually. This is a Ruby on Rails construct that serves as a wrapper around SQL-standard DATETIME fields. These contain arbitrary dates and can represent nearly any point in time as the range of expression is typically very large.

DateTime.new
# => Mon, 01 Jan -4712 00:00:00 +0000

所以令人放心的是,DateTime可以处理博客亚里士多德的帖子。

So it's reassuring that DateTime can handle blog posts from Aristotle.

当选择一个时,现在的区别是有点主观。历史上,DateTime已经提供了更好的选择,以日历方式操作它,但是许多这些方法已经移植到Time,至少在Rails环境中。

When choosing one, the differences are somewhat subjective now. Historically DateTime has provided better options for manipulating it in a calendar fashion, but many of these methods have been ported over to Time as well, at least within the Rails environment.

这篇关于Ruby中DateTime和Time之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆