Ruby, check if date is a weekend?

后端 未结 7 1544
灰色年华
灰色年华 2021-02-02 08:51

I have a DailyQuote model in my rails application which has a date and price for a stock. Data in the database has been captured for this model

相关标签:
7条回答
  • 2021-02-02 09:31
    weekend_days = [0,6]
    if (self.start_date.to_date..self.end_date.to_date).to_a.select {|k| weekend_days.include?(k.wday)}.present?
      # you code
    end
    
    0 讨论(0)
  • 2021-02-02 09:40

    since rails v5:

    Date.current.on_weekend?
    

    References:

    • api-doc
    • rails docu
    0 讨论(0)
  • 2021-02-02 09:41

    TFM shows an interesting way to identifying the day of the week:

    t = Time.now
    t.saturday?    #=> returns a boolean value
    t.sunday?      #=> returns a boolean value
    
    0 讨论(0)
  • 2021-02-02 09:46
    class Time
      def is_weekend?
        [0, 6, 7].include?(wday)
      end
    end
    
    time = Time.new
    
    puts "Current Time : " + time.inspect
    puts time.is_weekend?
    
    0 讨论(0)
  • 2021-02-02 09:48
    require 'date'
    today = Date.today
    ask_price_for = (today.wday == 6) ? today - 1 : (today.wday == 0) ? today - 2 : today
    

    or

    require 'date'
    today = Date.today
    ask_price_for = (today.saturday?) ? today - 1 : (today.sunday?) ? today - 2 : today  
    

    ask_price_for now holds a date for which you would want to ask the price for.

    Getting the actual price which is corresponding to you date depends on your Model and your ORM-Library (i.e. ActiveRecord).

    0 讨论(0)
  • 2021-02-02 09:55

    Date.today.instance_eval { saturday? || sunday? }

    0 讨论(0)
提交回复
热议问题