如何计算红宝石日期中的星期几?

如何在Ruby中计算日期的星期几? 例如,2010年10月28日是=星期四

Nisanio asked 2019-11-06T18:37:43Z
9个解决方案
64 votes

我之所以使用它,是因为我不想去日期文档中查找strftime语法,而不是在那里找到它并且必须记住它在时间文档中。

require 'date'

class Date
  def dayname
     DAYNAMES[self.wday]
  end

  def abbr_dayname
    ABBR_DAYNAMES[self.wday]
  end
end

today = Date.today

puts today.dayname
puts today.abbr_dayname
steenslag answered 2019-11-06T18:38:01Z
61 votes

看一下Date类的引用。 拥有日期对象后,您就可以整天完成dateObj.strftime('%A'),或将缩写天完成dateObj.strftime('%a')。 您还可以将dateObj.wday用作星期几的整数值,并根据需要使用它。

mway answered 2019-11-06T18:38:25Z
27 votes
time = Time.at(time)    # Convert number of seconds into Time object.
puts time.wday    # => 0: Day of week: 0 is Sunday
brian_d answered 2019-11-06T18:38:43Z
20 votes
Date.today.strftime("%A")
=> "Wednesday"

Date.today.strftime("%A").downcase  
=> "wednesday"
Abhi answered 2019-11-06T18:39:00Z
7 votes

快速,肮脏且易于本地化:

days = {0 => "Sunday",
1 => "Monday", 
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday"}

puts "It's #{days[Time.now.wday]}"
Andreas Bergström answered 2019-11-06T18:39:24Z
6 votes

使用红宝石即可直接使用,无需:

Time.now.strftime("%A").downcase #=> "thursday"
Niels Kristian answered 2019-11-06T18:39:48Z
5 votes

正如@mway所说,您可以在任何Date对象上使用date.strftime(“%A”)来获取星期几。

如果您很幸运,Date.parse可能一口气让您从String到星期几:

def weekday(date_string)
  Date.parse(date_string).strftime("%A")
end

这适用于您的测试用例:

weekday("October 28 of 2010") #=> "Thursday"
Adam Tanner answered 2019-11-06T18:40:25Z
5 votes

说我有date = Time.now.to_date然后date.strftime("%A")将打印星期几的名称,并在一周中的几天内输入date.wday

Saqib R. answered 2019-11-06T18:40:50Z
2 votes

在您的时间对象中,使用属性.wday获取与星期几相对应的数字,例如 如果.wday返回0,则您的日期为Sunday,1 Monday等。

George Johnston answered 2019-11-06T18:41:15Z
translate from https://stackoverflow.com:/questions/4044574/how-can-i-calculate-the-day-of-the-week-of-a-date-in-ruby