Ruby中的日期和时间类

Ruby数据和时间类

在用任何语言编写的任何程序中,您可能需要在任何时间获取该时刻的系统日期和时间。Ruby通过与日期和时间相关的三个类为您提供便利:

  • 日期

  • 约会时间

  • 时间

如果使用日期,则需要了解一些与日期有关的术语,例如:

  1. 日历日期:您必须熟悉该术语。它是不同年份的日历月的特定日期。

  2. 原始日期:当您借助普通年份确定特定的日期时。这是一个序数日期。

  3. 周日期:是日历周和天数的组合。包括不同年份的第一个星期四的一周是该年的第一个日历周。

  4. 朱利安天数:是公元前4713年1月1日中午以来日期的一种演变。

现在,让我们详细讨论上面提到的与日期和时间相关的所有这三个类。

1)日期

日期类对象是可变的,意味着它们无法在执行过程中的任何时间修改自己。在实现日期对象之前,您将需要在Ruby代码中包括日期类。您可以使用:: new,:: parse,:: today,:: jd和:: strptime创建日期对象。

现在让我们看看如何借助示例创建日期对象

=begin
Ruby program to show the implementation of 
date class.
=end

require 'date'

puts Date.new(2020,4,12)            
puts Date.jd(2451877)               
puts Date.ordinal(2020,3)         
puts Date.commercial(2020,12,6)     
puts Date.parse('2020-02-03')    
puts Date.strptime('03-02-2020', '%m-%d-%Y')

输出:

2020-04-12
2000-11-28
2020-01-03
2020-03-21
2020-02-03
2020-03-02

这里,

  1. new:new方法将根据传递的参数创建一个新对象。

  2. jd:提供当地时间,并返回儒略日。

  3. ordinal:根据传递的参数创建日期对象。参数可以是负数或正数,但永远不能为零。

  4. commercial:根据提供的星期日期创建日期对象。参数可以是负数或正数,但永远不能为零。

  5. parse:它创建一个日期对象并解析日期和时间的表示形式。

  6. strptime:在解析提供的时间日期表示形式和指定模板之后,它返回解析元素的哈希值。

2)日期时间

此类是Date类的子类。您可以借助DateTime.new,DateTime.ordinal,DateTime.parse,DateTime.jd,DateTime.commercial,DateTime.now等创建DateTime类的对象。让我们看一下它的例子:

=begin
Ruby program to show the implementation of 
DateTime class.
=end

require 'date'   
  
d = DateTime.parse('12th Oct 2020 13:37:05+05:40')   
                       
puts d.hour                 
puts d.min                 
puts d.sec                  
puts d.offset

输出结果

13
37
5
17/72

在上面的代码中,我们将日期解析后存储在对象中。然后,我们调用它的多个方法,例如小时,分钟,秒和偏移量。

3)时间

时间类DateDateTime类的抽象。您可以在:: new的帮助下创建其对象,这将使用当前系统的时间。您可以在参数列表中传递年,月,日,小时,分钟,秒。下面是一个示例:

=begin
Ruby program to show the implementation of 
Time class.
=end

time1 = Time.new

puts "Printing Current Time: "+ time1.inspect
puts time1.year
puts time1.month   
puts time1.day     
puts time1.hour    
puts time1.min     
puts time1.sec     
puts time1.zone

输出结果

Printing Current Time: 2019-09-25 06:26:58 +0530
2019
9
25
6
26
58
India Standard Time