DateTime和Ruby中的时间之间的差异 [英] Difference between DateTime and Time in Ruby

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

问题描述

在Ruby中, DateTime Time 类之间有什么区别?哪些因素会导致我选择一个或一个其他?

What's the difference between DateTime and Time classes in Ruby 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之前的版本中,在许多系统上,时间表示为32位带符号的值,描述了自1月1日以来的秒数。 ,即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提供了更好的选项以日历方式进行操作,但是至少在Rails环境中,许多这些方法也已移植到Time上。

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.

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

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