Ruby 中日期时间和时间的区别 [英] Difference between DateTime and Time in Ruby

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

问题描述

Ruby 中的 DateTimeTime 类之间有什么区别,哪些因素会导致我选择其中之一?

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 位有符号值,描述自 UTC 时间 1970 年 1 月 1 日以来的秒数,这是 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 中日期时间和时间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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