How can I calculate the day of the week of a date in ruby?
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
How to get the date by day of the week ruby
To get the current day in Rails, you can use:
Date.today
To get the previous Saturday (since today is Monday 3rd July
, that's Saturday 1st July
), you can use:
Date.today.beginning_of_week(:saturday)
Or, if what you actually wanted was the previous week's Saturday (Saturday 24th June
), then you can use:
Date.today.weeks_ago(1).beginning_of_week(:saturday)
Or, if you prefer:
1.week.ago.beginning_of_week(:saturday)
...However, note that the above will return an ActiveSupport::TimeWithZone
object rather than a Date
object - so will behave slightly differently.
Have a read through the rails documentation - in particular, the ActiveSupport
extensions to ruby's Date
class to see what methods are available.
If, for some reason, you needed to do this in pure ruby
(i.e. without the above mentioned ActiveSupport
extensions that come bundled with rails
), then you could instead utilise the Date.parse
method:
require 'date'
Date.parse("Saturday") - 7
# => Sat, 01 Jul 2017
In order to convert your Date
(or similar) object to the string format you desire ("24-June-2017"
), you can use ruby's strftime
method:
(Date.parse("Saturday") - 7).strftime('%d-%B-%Y')
In rails, it is a common convention to place such custom date formats in a locale or initializer to avoid repetition. You can then reference this format by name:
# config/initializers/date_formats.rb
# (Call this whatever you want!)
Date::DATE_FORMATS[:calendar] = '%d-%B-%Y'
# Anywhere else in the rails app
Date.today.beginning_of_week(:saturday).to_s(:calendar)
# => "01-July-2017"
Rails - Determine the day of the week
In Ruby 2.1.1, the Date class has a friday?
method
Returns true if the date is a friday
First, require the date
library
require 'date'
Then create a new date instance with the current date. Here's an example
current_time = Time.now
year = current_time.year
month = current_time.month
day = current_time.day
date = Date.new(year, month, day)
date.friday?
=> true
Depending on your coding preferences, you could DRY this up even more
date = Date.new(Time.now.year, Time.now.month, Time.now.day)
=> #<Date: 2016-03-11 ((2457459j,0s,0n),+0s,2299161j)>
date.friday?
If you'd like to solve this without a Boolean method, (the ones that usually end in a question mark and return either true
or false
), such as when you're comparing to a database column, you can use the Date#wday
method. Keep in mind, this returns a number in the range (0..6) with 0 representing Sunday. This means that you want to pass in 5 to check for Friday.
if date.wday == 5
// Do something
end
Also, if you are working with business hours, it might be easiest to use the business_time
gem
You can also include the holidays
gem with business_time
.
First, install the gems
gem install business_time
gem install holidays
Then require the gem
require 'business_time'
require 'holidays'
Find out if today is a workday
Date.today.workday?
and is a holiday
You can now use something like this to determine if today is a holiday
Holidays.on(date, :us).empty?
and is between office working hours
The definition of office hours varies from person to person. There's no set-in-stone answer. However, with the business_time
gem, you can set configurations
BusinessTime::Config.beginning_of_workday = "8:30 am"
BusinessTime::Config.end_of_workday = "5:30 pm"
Sources
Ruby
http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html#method-i-wday
http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html#method-i-friday-3F
Gems
https://github.com/bokmann/business_time
https://github.com/holidays/holidays
How do I get day of the week from a date object?
Looking at the Ruby docs for strftime
Time.now.strftime("%A, %d/%m/%Y")
=> "Wednesday, 04/01/2012"
The %A
character is the full day name.
Ruby code to get the date of next Monday (or any day of the week)
require 'date'
def date_of_next(day)
date = Date.parse(day)
delta = date > Date.today ? 0 : 7
date + delta
end
Date.today
#=>#<Date: 2011-10-28 (4911725/2,0,2299161)>
date_of_next "Monday"
#=>#<Date: 2011-10-31 (4911731/2,0,2299161)>
date_of_next "Sunday"
#=>#<Date: 2011-10-30 (4911729/2,0,2299161)>
Ruby find next Thursday (or any day of the week)
DateTime.now.next_week.next_day(3)
As @Nils Riedemann pointed out:
Keep in mind that it will not get the next thursday, but the thursday
of the next week. eg. If tomorrow was thursday, it won't return
tomorrow, but next week's thursdays.
Here is an excerpt of some code I've written recently which handles the missing case.
require 'date'
module DateTimeMixin
def next_week
self + (7 - self.wday)
end
def next_wday (n)
n > self.wday ? self + (n - self.wday) : self.next_week.next_day(n)
end
end
# Example
ruby-1.9.3-p194 :001 > x = DateTime.now.extend(DateTimeMixin)
=> #<DateTime: 2012-10-19T15:46:57-05:00 ... >
ruby-1.9.3-p194 :002 > x.next_week
=> #<DateTime: 2012-10-21T15:46:57-05:00 ... >
ruby-1.9.3-p194 :003 > x.next_wday(4)
=> #<DateTime: 2012-10-25T15:46:57-05:00 ... >
How to get the date of this Wednesday , this Thursday etc. in Rails
You could use #next_occurring
pry(main)> Time.zone.today.beginning_of_week
Mon, 20 Jan 2020
pry(main)> Time.zone.today.beginning_of_week.next_occurring(:thursday)
Thu, 23 Jan 2020
Given date and day in week, find the closest date in future
This is a pure Ruby solution.
require 'date'
d = Date.strptime('9-4-2016', '%d-%m-%Y')
#=> #<Date: 2016-04-09 ((2457488j,0s,0n),+0s,2299161j)>
d + (1 - d.wday) % 7
#=> #<Date: 2016-04-11 ((2457490j,0s,0n),+0s,2299161j)>
1
is Monday's offset. d.wday #=> 6
.
I have assumed that if the date falls on a Monday, the "closest" Monday is the same day. If it is to be the following Monday, use:
d + (d.wday == 1) ? 7 : (1 - d.wday) % 7
How can I display the days of the week?
You can use a range and iterate through:
<% (Date.today.beginning_of_week(:sunday)...Date.today.end_of_week).each do |date| %>
<p><%= date.strftime('%a %d') %></p>
<% end %>
Will give you:
<p>Sun 28</p>
<p>Mon 29</p>
<p>Tue 30</p>
<p>Wed 01</p>
<p>Thu 02</p>
<p>Fri 03</p>
<p>Sat 04</p>
Note that we're using ...
instead of ..
for the range.
How can I output the day of week with embedded ruby?
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.
Copy from here
So Time.now.strftime("%A")
and in your case
<h6>
<%= Time.now.strftime("%A, %B %d. %Y") %>
</h6>
Easiest to test this is the rails c
. To remove the leading zero on the %d
use %-d
instead.
Related Topics
How to Do Static Content in Rails
Parallel Assignment Operator in Ruby
Why Do Two Strings Separated by Space Concatenate in Ruby
How to Do Relative Time in Rails
How to Compile and Statically Link Ruby Libs for Docker
In Ruby on Rails, Are '#Encoding: Utf-8' and 'Config.Encoding = "Utf-8"' Different
Test If Variable Matches Any of Several Strings W/O Long If-Elsif Chain, or Case-When
Correct Way to Populate an Array with a Range in Ruby
Rails Respond_To Format.Js API
Haml: Append Class If Condition Is True in Haml
Long Running Delayed_Job Jobs Stay Locked After a Restart on Heroku
Getting a "Bad Interpreter" Error When Using Brew
Serve Current Directory from Command Line
Can't Install Rails on MAC Os Catalina