Calculate number of business days between two days - ruby-on-rails

I need to calculate the number of business days between two dates. How can I pull that off using Ruby (or Rails...if there are Rails-specific helpers).
Likewise, I'd like to be able to add business days to a given date.
So if a date fell on a Thursday and I added 3 business days, it would return the next Tuesday.

Take a look at business_time. It can be used for both the things you're asking.
Calculating business days between two dates:
wednesday = Date.parse("October 17, 2018")
monday = Date.parse("October 22, 2018")
wednesday.business_days_until(monday) # => 3
Adding business days to a given date:
4.business_days.from_now
8.business_days.after(some_date)
Historical answer
When this question was originally asked, business_time didn't provide the business_days_until method so the method below was provided to answer the first part of the question.
This could still be useful to someone who didn't need any of the other functionality from business_time and wanted to avoid adding an additional dependency.
def business_days_between(date1, date2)
business_days = 0
date = date2
while date > date1
business_days = business_days + 1 unless date.saturday? or date.sunday?
date = date - 1.day
end
business_days
end
This can also be fine tuned to handle the cases that Tipx mentions in the way that you would like.

We used to use the algorithm suggested in the mikej's answer and discovered that calculating 25,000 ranges of several years each takes 340 seconds.
Here's another algorithm with asymptotic complexity O(1). It does the same calculations in 0.41 seconds.
# Calculates the number of business days in range (start_date, end_date]
#
# #param start_date [Date]
# #param end_date [Date]
#
# #return [Fixnum]
def business_days_between(start_date, end_date)
days_between = (end_date - start_date).to_i
return 0 unless days_between > 0
# Assuming we need to calculate days from 9th to 25th, 10-23 are covered
# by whole weeks, and 24-25 are extra days.
#
# Su Mo Tu We Th Fr Sa # Su Mo Tu We Th Fr Sa
# 1 2 3 4 5 # 1 2 3 4 5
# 6 7 8 9 10 11 12 # 6 7 8 9 ww ww ww
# 13 14 15 16 17 18 19 # ww ww ww ww ww ww ww
# 20 21 22 23 24 25 26 # ww ww ww ww ed ed 26
# 27 28 29 30 31 # 27 28 29 30 31
whole_weeks, extra_days = days_between.divmod(7)
unless extra_days.zero?
# Extra days start from the week day next to start_day,
# and end on end_date's week date. The position of the
# start date in a week can be either before (the left calendar)
# or after (the right one) the end date.
#
# Su Mo Tu We Th Fr Sa # Su Mo Tu We Th Fr Sa
# 1 2 3 4 5 # 1 2 3 4 5
# 6 7 8 9 10 11 12 # 6 7 8 9 10 11 12
# ## ## ## ## 17 18 19 # 13 14 15 16 ## ## ##
# 20 21 22 23 24 25 26 # ## 21 22 23 24 25 26
# 27 28 29 30 31 # 27 28 29 30 31
#
# If some of the extra_days fall on a weekend, they need to be subtracted.
# In the first case only corner days can be days off,
# and in the second case there are indeed two such days.
extra_days -= if start_date.tomorrow.wday <= end_date.wday
[start_date.tomorrow.sunday?, end_date.saturday?].count(true)
else
2
end
end
(whole_weeks * 5) + extra_days
end

business_time has all the functionallity you want.
From the readme:
#you can also calculate business duration between two dates
friday = Date.parse("December 24, 2010")
monday = Date.parse("December 27, 2010")
friday.business_days_until(monday) #=> 1
Adding business days to a given date:
some_date = Date.parse("August 4th, 1969")
8.business_days.after(some_date) #=> 14 Aug 1969

Here is my (non gem and non holiday) weekday count example:
first_date = Date.new(2016,1,5)
second_date = Date.new(2016,1,12)
count = 0
(first_date...second_date).each{|d| count+=1 if (1..5).include?(d.wday)}
count

Take a look at Workpattern. It alows you to specify working and resting periods and can add/subtract durations to/from a date as well as calculate the minutes between two dates.
You can set up workpatterns for different scenarios such as mon-fri working or sun-thu and you can have holidays and whole or part days.
I wrote this as away to learn Ruby. Still need to make it more Ruby-ish.

Based on #mikej's answer. But this also takes into account holidays, and returns a fraction of a day (up to the hour accurancy):
def num_days hi, lo
num_hours = 0
while hi > lo
num_hours += 1 if hi.workday? and !hi.holiday?
hi -= 1.hour
end
num_hours.to_f / 24
end
This uses the holidays and business_time gems.

Simple script to calculate total number of working days
require 'date'
(DateTime.parse('2016-01-01')...DateTime.parse('2017-01-01')).
inject({}) do |s,e|
s[e.month]||=0
if((1..5).include?(e.wday))
s[e.month]+=1
end
s
end
# => {1=>21, 2=>21, 3=>23, 4=>21, 5=>22, 6=>22, 7=>21, 8=>23, 9=>22, 10=>21, 11=>22, 12=>22}

There are two problems with the most popular solutions listed above:
They involve loops to count every single day between each date (meaning that performance gets worse the further apart the dates are.
They are unclear about whether they count from the beginning of the day or the end. If you count from the morning, there is one weekday between Friday and Saturday. If you count from the night, there are zero weekdays between Friday and Saturday.
After stewing over it, I propose this solution that addresses both problems. The below takes a reference date and an other date and calculates the number of weekdays between them (returning a negative number if other is before the reference date). The argument eod_base controls whether counting is done from end of day (eod) or start of day. It could be written more compactly but hopefully it's relatively easy to understand and it doesn't require gems or rails.
require 'date'
def weekdays_between(ref,otr,eod_base=true)
dates = [ref,otr].sort
return 0 if dates[0] == dates[1]
full_weeks = ((dates[1]-dates[0])/7).floor
dates[eod_base ? 0 : 1] += (eod_base ? 1 : -1)
part_week = Range.new(dates[0],dates[1])
.inject(0){|m,v| (v.wday >=1 && v.wday <= 5) ? (m+1) : m }
return (otr <=> ref) * (full_weeks*5 + part_week)
end

Related

How to set two different scheduler for single Jenkins job

I just want to run the job twice per week. Every Sunday 11 PM and every Friday 11 pm I just want to trigger the job automatically. I successfully implemented for one scheduler but not sure how to use two in single .
Sunday scheduler :
H 11 * * 0
Friday scheduler:
H 11 * * 6
For scheduling the job below pattern need to be followed:-
0 - Sun Sunday
1 - Mon Monday
2 - Tue Tuesday
3 - Wed Wednesday
4 - Thu Thursday
5 - Fri Friday
6 - Sat Saturday
7 - Sun Sunday
For your case you can follow the below:-
0 23 * * 0,5
You better understanding of "H" in Jobs Scheduler follow this:
Maybe something like this. Note there's a couple changes from your example, changed 11 to 23, 11 is 11am, 23 is 11pm and using 5 instead of 6 for Friday.
H 23 * * 0,5
But note with the "H" it isn't going to run at exactly 11pm, from the Jenkins docs:
The H symbol can be thought of as a random value over a range, but it
actually is a hash of the job name, not a random function, so that the
value remains stable for any given project.
If you want it to run closer to 11pm, maybe something like this
H(1-5) 23 * * 0,5

distance_of_time_in_words, smarter formatting?

Currently I'm using the following:
distance_of_time_in_words(tweet.created_at, Time.now + 30.minutes, include_seconds: false)
This works fine in most scenarios, but I'd like certain exceptions to be formatted differently, and the documentation is rather confusing for this scenario. (I also couldn't find any questions on here about it)
As an example, currently the function converts the time to this before 1 day has passed.
5 hours and 17 minutes ago
I'm using it for tweets posted and times such as
Tweeted 4 days, 8 hours, and 3 minutes
Seem a little long winded and unnecessarily specific.
Ideally I'd be like to be able to display:
less than a minute = the number of seconds ago
less than 1 hour = the amount of minutes
less than a day = the amount of hours
more than a day = the number of days
Is there a way of doing this?
Perhaps you want to use the distance_of_time_in_words helper:
0 <-> 29 secs # => less than a minute
30 secs <-> 1 min, 29 secs # => 1 minute
1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
and so on...
You can use that helper with just one argument. Something like this in your view should do the job:
Tweeted <%= time_ago_in_words(tweet.created_at) ago
Assuming tweet.created_at is about 29 hours ago it would render to:
Tweeted 1 day ago
see: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words
Here's a non-Rails solution, though it appears you are better off using Rails' distance_of_time_in_words helper. Looking through the documentation, the latter seems to offer tremendous flexibility.
require 'time'
SECS_PER_MIN = 60
SECS_PER_HOUR = 60 * SECS_PER_MIN
SECS_PER_DAY = 24 * SECS_PER_HOUR
SECS_PER_WEEK = 7 * SECS_PER_DAY
SECS_PER_YEAR = 365 * SECS_PER_DAY
SECS_PER_CENT = 100 * SECS_PER_YEAR
SECS_PER_MLNM = 10 * SECS_PER_CENT
SECS_PER_EON = 1_000_000 * SECS_PER_MLNM
def message(secs)
case secs
when (0...SECS_PER_MIN)
"#{secs} seconds"
when (SECS_PER_MIN...SECS_PER_HOUR)
"#{secs/SECS_PER_MIN} minutes"
when (SECS_PER_HOUR...SECS_PER_DAY)
"#{secs/SECS_PER_HOUR} hours"
when (SECS_PER_DAY...SECS_PER_WEEK)
"#{secs/SECS_PER_DAY} days"
when (SECS_PER_WEEK...SECS_PER_YEAR)
"#{secs/SECS_PER_WEEK} weeks"
when (SECS_PER_YEAR...SECS_PER_CENT)
"#{secs/SECS_PER_YEAR} years"
when (SECS_PER_CENT...SECS_PER_MLNM)
"#{secs/SECS_PER_CENT} centuries"
when (SECS_PER_MLNM...SECS_PER_EON)
"#{secs/SECS_PER_MLNM} millenia"
else
"#{secs/SECS_PER_EON} eons"
end << " ago"
end
You would call message with something like:
message(Time.now-tweet_time)
Let's try it.
message(10) #=> "10 seconds ago"
message(1_000) #=> "16 minutes ago"
message(20_000) #=> "5 hours ago"
message(300_000) #=> "3 days ago"
message(10_000_000) #=> "16 weeks ago"
message(1_000_000_000) #=> "31 years ago"
message(25_000_000_000) #=> "7 centuries ago"
message(1_300_000_000_000) #=> "41 millenia ago"
message(100_000_000_000_000_000) #=> "3 eons ago"
You could prettify it by changing, for example,
when (SECS_PER_DAY...SECS_PER_WEEK)
"#{secs/SECS_PER_DAY} days"
to
when (SECS_PER_DAY...SECS_PER_WEEK)
n = secs/SECS_PER_DAY
n == 1 ? "1 day" : "#{n} days"
The output of distance_of_time_in_words (which is just an alias for time_ago_in_words) should look like this:
0 <-> 29 secs # => less than a minute
30 secs <-> 1 min, 29 secs # => 1 minute
1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
1 yr <-> 1 yr, 3 months # => about 1 year
1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
2 yrs <-> max time or date # => (same rules as 1 yr)
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words
That looks like what you want. Something must be overriding distance_of_time_in_words? I'm not sure why anything would do that, but that seems to be the case.

Can I set Jenkins' "Build periodically" to build every other Tuesday starting March 13?

I want to schedule Jenkins to run a certain job at 8:00 am every Monday, Wednesday Thursday and Friday and 8:00 am every other Tuesday.
Right now, the best I can think of is:
# 8am every Monday, Wednesday, Thursday, and Friday:
0 8 * * 1,3-5
# 8am on specific desired Tuesdays, one line per month:
0 8 13,27 3 2
0 8 10,24 4 2
0 8 8,22 5 2
0 8 5,19 6 2
0 8 3,17,31 7 2
0 8 14,28 8 2
0 8 11,25 9 2
0 8 9,23 10 2
0 8 6,20 11 2
0 8 4,18 12 2
which is is fine (if ugly) for the remainder of 2012, but it almost certainly won't do what I want in 2013.
Is there a more concise way to do this, or one that's year-independant?
This is something that comes up quite often, see e.g. this document, this forum thread or this stackoverflow question.
The answer is basically no. What I would do in your situtation is to run the job every Tuesday and have the first build step check whether to actually run by e.g. checking whether a file exists and only running if it doesn't. If it exists, it would be deleted so that the job can run the next time this check occurs. You would of course also have to check whether it's Tuesday.
I got you fam: crontab.guru
10 22 1-7,14-21,28-31 * 6
If you abandon every other Tuesday, and can be satisfied with the first and third Tuesdays a month, the following should work:
0 9 1-7 * 2
0 9 15-21 * 2
You're running every day from 1-7, but only on Tuesday, and every day from 15-21, again only on Tuesday. A Tuesday will occur only once in each of those intervals.
Yes, it's not strictly every other week, as a 5-Tuesday month will throw off your cadence, but here you have a predictable job schedule that doesn't need to be adjusted in Jenkins as time goes on.
I use Excel to generate the cron expressions. The following formulas generate every other Monday at 8:00 AM starting from Oct 22.
A B C D
1 41204 =MONTH(A1) =DAY(A1) =CONCATENATE("0 8 ", C1, " ", B1, " 1")
2 =A1+14 =MONTH(A2) =DAY(A2) =CONCATENATE("0 8 ", C2, " ", B2, " 1")
This generates
A B C D
1 22-Oct 10 22 0 8 22 10 1
2 5-Nov 11 5 0 8 5 11 1
Just auto fill Row 2 to get additional days. I'm not sure how many separate expressions you can give to Jenkins. I know it works with 26 expressions.

Rails times oddness : "x days from now"

when users sign up to one of my sites for a free trial, i set their account expiry to be "14.days.from_now". Then on the home page i show how many days they have remaining, which i get with:
(user.trial_expires - Time.now)/86400
(because there are 86400 seconds in a day, ie 60 * 60 * 24)
The funny thing is, this comes out as more than 14, so gets rounded up to 15. On closer investigation in the console this happens for just two days in the future (if you know what i mean). eg
>> Time.now
=> Fri Oct 29 11:09:26 0100 2010
>> future_1_day = 1.day.from_now
=> Sat, 30 Oct 2010 11:09:27 BST 01:00
#ten past eleven tomorrow
>> (future_1_day - Time.now)/86400
=> 0.999782301526931
#less than 1, what you'd expect right?
>> future_2_day = 2.day.from_now
=> Sun, 31 Oct 2010 11:09:52 GMT 00:00
>> (future_2_day - Time.now)/86400
=> 2.04162248861183
#greater than 2 - why?
I thought maybe it was to do with timezones - i noticed that the time from 1.day from now was in BST and the time 2 days from now was in GMT. So, i tried using localtime and got the same results!
>> future_2_day = 2.day.from_now.localtime
=> Sun Oct 31 11:11:24 0000 2010
>> (future_2_day - Time.now)/86400
=> 2.04160829127315
>> (future_2_day - Time.now.localtime)/86400
=> 2.04058651585648
I then wondered how big the difference is, and it turns out that it is exactly an hour out. So it looks like some time zone weirdness, or at least something to do with time zones that i don't understand. Currently my time zone is BST (british summer time) which is one hour later than UTC at the moment (till this sunday at which point it reverts to the same as UTC).
The extra hour seems to be introduced when i add two days to Time.now: check this out. I start with Time.now, add two days to it, subtract Time.now, then subtract two days of seconds from the result, and am left with an hour.
It just occurred to me, in a head slapping moment, that this is occurring BECAUSE the clocks go back on sunday morning: ie at 11.20 on sunday morning it will be two days AND an extra hour from now. I was about to delete all of this post, but then i noticed this: i thought 'ah, i can fix this by using (24*daynum).hours instead of daynum.days, but i still get the same result: even when i use seconds!
>> (Time.now + (2*24).hours - Time.now) - 86400*2
=> 3599.99969500001
>> (Time.now + (2*24*3600).seconds - Time.now) - 86400*2
=> 3599.999855
So now i'm confused again. How can now plus two days worth of seconds, minus now, minus two days worth of seconds be an hour worth of seconds? Where does the extra hour sneak in?
As willcodejavaforfood has commented, this is due to daylight saving time which ends this weekend.
When adding a duration ActiveSupport has some code in it to compensate for if the starting time is in DST and the resulting time isn't (or vice versa).
def since(seconds)
f = seconds.since(self)
if ActiveSupport::Duration === seconds
f
else
initial_dst = self.dst? ? 1 : 0
final_dst = f.dst? ? 1 : 0
(seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f
end
rescue
self.to_datetime.since(seconds)
end
If you have 11:09:27 and add a number of days you will still get 11:09:27 on the resulting day even if the DST has changed. This results in an extra hour when you come to do calculations in seconds.
A couple of ideas:
Use the distance_of_time_in_words helper method to give the user an indication of how long is left in their trial.
Calculate the expiry as Time.now + (14 * 86400) instead of using 14.days.from_now - but some users might claim that they have lost an hour of their trial.
Set trials to expire at 23:59:59 on the expiry day regardless of the actual signup time.
You could use the Date class to calculate the number of days between today and the expire date.
expire_date = Date.new(user.trial_expires.year, user.trial_expires.month, user.trial_expires.day)
days_until_expiration = (expire_date - Date.today).to_i
Use since, example:
14.days.since.to_date

Ruby on Rails - Working with times

If in a database (MySQL), I have a datetime column (ex. 1899-12-30 19:00:00), how do I sum 1 day to it?
Following http://corelib.rubyonrails.org/classes/Time.html#M000240
If I want to add 1 day, it actually adds 60*60*24 days (86,400 days)
r=Record.find(:first)
=>Sat, 30 Dec 1899 19:00:00 -0600
r.date + (60*60*24)
=>Fri, 20 Jul 2136 19:00:00 -0600
But if I do this it actually adds 1 day:
t = Time.now
=>Mon Jun 14 10:32:51 -0600 2010
t + (60 * 60 * 24)
=>Tue Jun 15 10:33:21 -0600 2010
I guess it has to do with the format...how do I make this work?
You're actually adding 86,400 seconds (60 seconds * 60 minutes * 24 hours).
ActiveSupport has some built in helper methods for dealing with time:
Time.now + 1.day + 15.hours
In Rails,
its very simple to use times.
r = Record.find(:first)
r.created_at + 1.day # this will give you a day to one day ahead )
r.created_at + 2.days + 15.hours + 30.minutes + 5.seconds
or use Time.now
Also, if you want take a look at the by_star plugin/gem its makes some querying etc very easy.

Resources