How can I calculate the day of the week of a date in ruby?

前端 未结 10 569
抹茶落季
抹茶落季 2020-12-01 05:05

How can I calculate the day of the week of a date in Ruby? For example, October 28 of 2010 is = Thursday

相关标签:
10条回答
  • 2020-12-01 05:38
    time = Time.at(time)    # Convert number of seconds into Time object.
    puts time.wday    # => 0: Day of week: 0 is Sunday
    
    0 讨论(0)
  • 2020-12-01 05:40

    In your time object, use the property .wday to get the number that corresponds with the day of the week, e.g. If .wday returns 0, then your date is Sunday, 1 Monday, etc.

    0 讨论(0)
  • 2020-12-01 05:44

    basically the same answer as Andreas

    days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
    today_is = days[Time.now.wday]
    
    if today_is == 'tuesday'
      ## ...
    end
    
    0 讨论(0)
  • 2020-12-01 05:45

    I have used this because I hated to go to the Date docs to look up the strftime syntax, not finding it there and having to remember it is in the Time docs.

    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
    
    0 讨论(0)
提交回复
热议问题