Rails - Determine the day of the week - ruby-on-rails

So DateTime.current returns Fri, 11 Mar 2016 19:34:10 +0000.
How can I determine the day of the week. For example, if DateTime.current is Friday(just the day of the week, regardless of the date)?
DateTime.current == DateTime.parse("Friday") Won't work because DateTime.parse("Friday") returns Fri, 11 Mar 2016 00:00:00 +0000 which is not the same.
How can I check whether only the date or only the time equals to a specific value?
Thanks in advance!
Basically I want to see if DateTime.current is not a weekend nor a public holiday and is between office working hours

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

You can use something like the following:
day = DateTime.now.strftime("%A")
This will return the day of the week with the full name, capitalized. You can also get the abbreviation like this:
day = DateTime.now.strftime("%a")
You can also use %u or %w to get the day of the week as an integer. Friday would be 5.
DateTime.now.strftime("%u") == 5 # True if Friday
You can check here for more capabilities:
APIdock documentation

Check this-
require 'date'
today = DateTime.current.to_date
if today.Friday?
puts "Today is a Friday!"
end

Related

Rails cant save correct date into database

I have a date format like this "18/12/15" as input (it is a string)
18 => day
12 => month
15 => year (2015)
I am trying to store it in my db in a date column but it doesnt save the proper date (for the previous exemple I get Sat, 15 Dec 2018 whereas I should get something like day, 18 Dec 2015.)
How can I fix that
You could use strptime:
require 'date'
Date.strptime('18/12/15', '%d/%m/%y')
#<Date: 2015-12-18 ((2457375j,0s,0n),+0s,2299161j)>
You want to define a date with the order of day, month, year, while, due to the locale your intention is interpreted as year, month, day.
You can do one of the following:
pass the parameters in inverted order
implement a method which gets the parameters in the correct order and inverts them
set the locale to the one you intend to use
use strptime, as spickermann described

.change function is not working for Dates for even number of months in ruby

Hi I have define this method
def change_date
date = Date.today
start_date = date.change(year: 2015, month: (2 * 3)).at_beginning_of_quarter
p 'aaaaaa'
p start_date
end
give me invalid date error .change is not working or am I doing it in a wrong way please guide me how to solve this. Thanx in advance.
This is because the month you are specifying doesn't have the current day.
I mean the current month (July) has 31 days but the month you're setting (June) has only 30 days. You can change your code like so:
# in Rails:
date = Date.today.beginning_of_month # or Date.today.change(day: 1)
Then chain your 'change' in front of the date variable.
This actually happens, because today is the 31 of July, and not all months have 31 days in it, for example June, the 6th month, has only 30 days in it.

Ruby On Rails, week number is not the correct one (-1)

I need the current week number, if I'm not totally mistaken it's week 51 right now? However when testing it in the console I get this.
Time.now
=> 2013-12-19 11:08:25 +0100
Time.now.strftime('%U')
=> "50"
Date.today
=> Thu, 19 Dec 2013
Date.today.strftime("%U").to_i
=> 50
Why is that?
Time.now.strftime('%V') will give you the week number according to ISO 8601.
why is that?
according to %U or %W, The days in the year before the first week are in week 0 (00..53).
with %V (as #Graeme McLean wrote), The days in the year before the first week are in the last week of
the previous year (01..53).
From here.
Hmm, I'm unsure as to why it is that way, but to get the correct one using Ruby, I use this:
require 'Date'
week_number = Date.today.cweek #=> 51

Ruby, check if date is a weekend?

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 including weekends. The weekend price values have been set as 0.
I want to change all the weekend prices for Saturday and Sunday to whatever the price was on Friday. What is the best way to do this in Ruby? To identify if a date falls on a Sat or Sun and change its value to the Fri of that weekend?
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
The simplest approach:
today = Date.today
if today.saturday? || today.sunday?
puts "Today is a weekend!"
end
You can also do this for any other day of the week. Ruby is fantastic and offers a lot of cool methods like this. I suggest when you get stumped take a look at what's available to the class by running .methods on it. So if you run Date.today.methods you will see these available.
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).
class Time
def is_weekend?
[0, 6, 7].include?(wday)
end
end
time = Time.new
puts "Current Time : " + time.inspect
puts time.is_weekend?
since rails v5:
Date.current.on_weekend?
References:
api-doc
rails docu
Date.today.instance_eval { saturday? || sunday? }
Checking of weekend days (Saturday and Sunday) in the range of two dates in ruby
weekend_days = [0,6]
if (start_date.to_date..end_date.to_date).to_a.select {|k| weekend_days.include?(k.wday)}.present?
# you code
end

Rails: Is there away to get the Date object that is the closest Monday to today?

Given a date, how do I find the nearest Monday in Rails?
I know I can do things like:
Date.tomorrow
Date.today
Is there something like Date.nearest :monday ?
The commercial method on the Date object will let you do this. This example will get you the next Monday.
Date.commercial(Date.today.year, 1+Date.today.cweek, 1)
If you need the next or previous Monday, whichever is closest, you can do:
Date.commercial(Date.today.year, Date.today.cwday.modulo(4)+Date.today.cweek, 1)
I can't execute this right now, so forgive me if there are syntax errors.
It's a little bit tricky, but not so hard to calculate.
Use ActiveSupport::DateAndTimeCalculations#end_of_week to calculate end of a week, this method accepts a start_day parameter that is used to indicate start day of the week (it's :monday by default). They even have implemented sunday method.
The trick is the following: if you want to calculate closest Monday, you may calculate it as a end of the week which starts on Tuesday (Tue => 1st day, Wed => 2nd day, ..., Mon => 7th day which is also end of the week).
So all you need to do is:
# it will return current date if today is Monday and nearest Monday otherwise
Date.today.end_of_week(:tuesday)
I know this is an old thread but it's always nice to keep it current for future seekers.
Let's assume today is say Friday the 19th of August. All I do to get my nearest Monday is this:
monday = Date.today.monday
Then from there you can go back a week or forward a week like this:
last_monday = monday.last_week
next_monday = monday.next_week
Assuming you want both directions: Date.today.beginning_of_week + 7*(Date.today.wday/5)
Untested, so you might need to finetune, but here you go:
def Date.nearest_monday
today = Date.today
wday = today.wday
if wday > 4 # over the half of the week
today + (7 - wday) # next monday
else
today - (1 + wday) # previous monday
end
end

Resources