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

前端 未结 10 568
抹茶落季
抹茶落季 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:23
    Date.today.strftime("%A")
    => "Wednesday"
    
    Date.today.strftime("%A").downcase  
    => "wednesday"
    
    0 讨论(0)
  • 2020-12-01 05:24

    Say i have date = Time.now.to_date then date.strftime("%A") will print name for the day of the week and to have just the number for the day of the week write date.wday.

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

    Works out of the box with ruby without requiring:

    Time.now.strftime("%A").downcase #=> "thursday"
    
    0 讨论(0)
  • 2020-12-01 05:30

    Take a look at the Date class reference. Once you have a date object, you can simply do dateObj.strftime('%A') for the full day, or dateObj.strftime('%a') for the abbreviated day. You can also use dateObj.wday for the integer value of the day of the week, and use it as you see fit.

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

    As @mway said, you can use date.strftime("%A") on any Date object to get the day of the week.

    If you're lucky Date.parse might get you from String to day of the week in one go:

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

    This works for your test case:

    weekday("October 28 of 2010") #=> "Thursday"
    
    0 讨论(0)
  • 2020-12-01 05:37

    Quick, dirty and localization-friendly:

    days = {0 => "Sunday",
    1 => "Monday", 
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday"}
    
    puts "It's #{days[Time.now.wday]}"
    
    0 讨论(0)
提交回复
热议问题