• Stars
    star
    487
  • Rank 86,998 (Top 2 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Time calculations using business hours.

biz

Gem Version repo-checks Code Climate Test Coverage

Time calculations using business hours.

Features

  • Support for:
    • Multiple intervals per day.
    • Multiple schedule configurations.
    • Intervals spanning the entire day.
    • Holidays.
    • Breaks (time-segment holidays).
    • Shifts (date-based intervals).
  • Second-level calculation precision.
  • Seamless Daylight Saving Time handling.
  • Schedule intersection.
  • Thread safety.

Anti-Features

  • No dependency on ActiveSupport.
  • No monkey patching by default.

Installation

Add this line to your application's Gemfile:

gem 'biz'

And then execute:

$ bundle

Or install it yourself as:

$ gem install biz

Configuration

Biz.configure do |config|
  config.hours = {
    mon: {'09:00' => '17:00'},
    tue: {'00:00' => '24:00'},
    wed: {'09:00' => '17:00'},
    thu: {'09:00' => '12:00', '13:00' => '17:00'},
    sat: {'10:00' => '14:00'}
  }

  config.shifts = {
    Date.new(2006, 1, 1) => {'09:00' => '12:00'},
    Date.new(2006, 1, 7) => {'08:00' => '10:00', '12:00' => '14:00'}
  }

  config.breaks = {
    Date.new(2006, 1, 2) => {'10:00' => '11:30'},
    Date.new(2006, 1, 3) => {'14:15' => '14:30', '15:40' => '15:50'}
  }

  config.holidays = [Date.new(2016, 1, 1), Date.new(2016, 12, 25)]

  config.time_zone = 'America/Los_Angeles'
end

Configured timestamps must be in either HH:MM or HH:MM:SS format.

Shifts act as exceptions to the hours configured for a particular date; that is, if a date is configured with both hours-based intervals and shifts, the shifts are in force and the intervals are disregarded.

Periods occurring on holidays are disregarded. Similarly, any segment of a period that overlaps with a break is treated as inactive.

If global configuration isn't your thing, configure an instance instead:

Biz::Schedule.new do |config|
  # ...
end

Note that times must be specified in 24-hour clock format and time zones must be IANA identifiers.

If you're operating in a threaded environment and want to use the same configuration across threads, save the configured schedule as a global variable:

$biz = Biz::Schedule.new

Usage

# Find the time an amount of business time *before* a specified starting time
Biz.time(30, :minutes).before(Time.utc(2015, 1, 1, 11, 45))

# Find the time an amount of business time *after* a specified starting time
Biz.time(2, :hours).after(Time.utc(2015, 12, 25, 9, 30))

# Calculations can be performed in seconds, minutes, hours, or days
Biz.time(1, :day).after(Time.utc(2015, 1, 8, 10))

# Find the previous business time
Biz.time(0, :hours).before(Time.utc(2016, 1, 8, 6))

# Find the next business time
Biz.time(0, :hours).after(Time.utc(2016, 1, 8, 20))

# Find the amount of business time between two times
Biz.within(Time.utc(2015, 3, 7), Time.utc(2015, 3, 14)).in_seconds

# Find the start of the business day
Biz.periods.on(Date.today).first.start_time

# Find the end of the business day
Biz.periods.on(Date.today).to_a.last.end_time

# Determine if a time is in business hours
Biz.in_hours?(Time.utc(2015, 1, 10, 9))

# Determine if a time is during a break
Biz.on_break?(Time.utc(2016, 6, 3))

# Determine if a time is during a holiday
Biz.on_holiday?(Time.utc(2014, 1, 1))

The same methods can be called on a configured instance:

schedule = Biz::Schedule.new

schedule.in_hours?(Time.utc(2015, 1, 1, 10))

All returned times are in UTC.

If a schedule will be configured with a large number of holidays and performance is a particular concern, it's recommended that holidays are filtered down to those relevant to the calculation(s) at hand before configuration to improve performance.

By dropping down a level, you can get access to the underlying time segments, which you can use to do your own custom calculations or just get a better idea of what's happening under the hood:

Biz.periods.after(Time.utc(2015, 1, 10, 10)).timeline
  .until(Time.utc(2015, 1, 17, 10)).to_a

#=> [#<Biz::TimeSegment start_time=2015-01-10 18:00:00 UTC end_time=2015-01-10 22:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-01-12 17:00:00 UTC end_time=2015-01-13 01:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-01-13 08:00:00 UTC end_time=2015-01-14 08:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-01-14 17:00:00 UTC end_time=2015-01-15 01:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-01-15 17:00:00 UTC end_time=2015-01-15 20:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-01-15 21:00:00 UTC end_time=2015-01-16 01:00:00 UTC>]

Biz.periods
  .before(Time.utc(2015, 5, 5, 12, 34, 57)).timeline
  .for(Biz::Duration.minutes(3_598)).to_a

#=> [#<Biz::TimeSegment start_time=2015-05-05 07:00:00 UTC end_time=2015-05-05 12:34:57 UTC>,
#  #<Biz::TimeSegment start_time=2015-05-04 16:00:00 UTC end_time=2015-05-05 00:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-05-02 17:00:00 UTC end_time=2015-05-02 21:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-04-30 20:00:00 UTC end_time=2015-05-01 00:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-04-30 16:00:00 UTC end_time=2015-04-30 19:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-04-29 16:00:00 UTC end_time=2015-04-30 00:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-04-28 07:00:00 UTC end_time=2015-04-29 07:00:00 UTC>,
#  #<Biz::TimeSegment start_time=2015-04-27 20:36:57 UTC end_time=2015-04-28 00:00:00 UTC>]

Day calculation semantics

Unlike seconds, minutes, or hours, a "day" is an ambiguous concept, particularly in relation to the vast number of potential schedule configurations. Because of that, day calculations are implemented with the principle of making the logic as straightforward as possible while knowing not all use cases will be satisfied out of the box.

Here's the logic that's followed:

Find the next day that contains business hours. Starting from the same minute on that day as the specified time, look forward (or back) to find the next moment in time that is in business hours.

Schedule intersection

An intersection of two schedules can be found using &:

schedule_1 = Biz::Schedule.new do |config|
  config.hours = {
    mon: {'09:00' => '17:00'},
    tue: {'10:00' => '16:00'},
    wed: {'09:00' => '17:00'},
    thu: {'10:00' => '16:00'},
    fri: {'09:00' => '17:00'},
    sat: {'11:00' => '14:30'}
  }

  config.shifts = {
    Date.new(2016, 7, 1) => {'10:00' => '13:00', '15:00' => '16:00'},
    Date.new(2016, 7, 2) => {'14:00' => '17:00'}
  }

  config.breaks = {
    Date.new(2016, 6, 2) => {'09:00' => '10:30', '16:00' => '16:30'},
    Date.new(2016, 6, 3) => {'12:15' => '12:45'}
  }

  config.holidays = [Date.new(2016, 1, 1), Date.new(2016, 12, 25)]

  config.time_zone = 'Etc/UTC'
end

schedule_2 = Biz::Schedule.new do |config|
  config.hours = {
    sun: {'10:00' => '12:00'},
    mon: {'08:00' => '10:00'},
    tue: {'11:00' => '15:00'},
    wed: {'16:00' => '18:00'},
    thu: {'11:00' => '12:00', '13:00' => '14:00'}
  }

  config.shifts = {
    Date.new(2016, 7, 1) => {'15:30' => '16:30'},
    Date.new(2016, 7, 5) => {'14:00' => '18:00'}
  }

  config.breaks = {
    Date.new(2016, 6, 3) => {'13:30' => '14:00'},
    Date.new(2016, 6, 4) => {'11:00' => '12:00'}
  }

  config.holidays = [
    Date.new(2016, 1, 1),
    Date.new(2016, 7, 4),
    Date.new(2016, 11, 24)
  ]

  config.time_zone = 'America/Los_Angeles'
end

schedule_1 & schedule_2

The resulting schedule will be a combination of the two schedules: an intersection of the intervals, a union of the breaks and holidays, and the time zone of the first schedule. Any configured shifts will be disregarded.

For the above example, the resulting schedule would be equivalent to one with the following configuration:

Biz::Schedule.new do |config|
  config.hours = {
    mon: {'09:00' => '10:00'},
    tue: {'11:00' => '15:00'},
    wed: {'16:00' => '17:00'},
    thu: {'11:00' => '12:00', '13:00' => '14:00'}
  }

  config.shifts = {
    Date.new(2016, 7, 1) => {'15:30' => '16:00'},
    Date.new(2016, 7, 5) => {'14:00' => '16:00'}
  }

  config.breaks = {
    Date.new(2016, 6, 2) => {'09:00' => '10:30', '16:00' => '16:30'},
    Date.new(2016, 6, 3) => {'12:15' => '12:45', '13:30' => '14:00'},
    Date.new(2016, 6, 4) => {'11:00' => '12:00'}
  }

  config.holidays = [
    Date.new(2016, 1, 1),
    Date.new(2016, 7, 4),
    Date.new(2016, 11, 24),
    Date.new(2016, 12, 25)
  ]

  config.time_zone = 'Etc/UTC'
end

Core extensions

Optional extensions to core classes (Date, Integer, and Time) are available for additional expressiveness:

require 'biz/core_ext'

75.business_seconds.after(Time.utc(2015, 3, 5, 12, 30))

30.business_minutes.before(Time.utc(2015, 1, 1, 11, 45))

5.business_hours.after(Time.utc(2015, 4, 7, 8, 20))

3.business_days.before(Time.utc(2015, 5, 9, 4, 12))

Time.utc(2015, 8, 20, 9, 30).business_hours?

Time.utc(2016, 6, 3, 12).on_break?

Time.utc(2014, 1, 1, 12).on_holiday?

Date.new(2015, 12, 10).business_day?

Contributing

Pull requests are welcome, but consider asking for a feature or bug fix first through the issue tracker. When contributing code, please squash sloppy commits aggressively and follow Tim Pope's guidelines for commit messages.

There are a number of ways to get started after cloning the repository.

To set up your environment:

script/bootstrap

To run the spec suite:

script/spec

To open a console with the gem and sample schedule loaded:

script/console

Alternatives

Copyright and license

Copyright 2015-19 Zendesk

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this gem except in compliance with the License.

You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

android-floating-action-button

Floating Action Button for Android based on Material Design specification
Java
6,374
star
2

maxwell

Maxwell's daemon, a mysql-to-json kafka producer
Java
3,891
star
3

cross-storage

Cross domain local storage, with permissions
JavaScript
2,190
star
4

samson

Web interface for deployments, with plugin architecture and kubernetes support
Ruby
1,443
star
5

ruby-kafka

A Ruby client library for Apache Kafka
Ruby
1,262
star
6

helm-secrets

DEPRECATED A helm plugin that help manage secrets with Git workflow and store them anywhere
Shell
1,159
star
7

curly

The Curly template language allows separating your logic from the structure of your HTML templates.
Ruby
591
star
8

racecar

Racecar: a simple framework for Kafka consumers in Ruby
Ruby
475
star
9

zendesk_api_client_rb

Official Ruby Zendesk API Client
Ruby
382
star
10

dropbox-api

Dropbox API Ruby Client
Ruby
362
star
11

zendesk_api_client_php

Official Zendesk API v2 client library for PHP
PHP
332
star
12

stronger_parameters

Type checking and type casting of parameters for Action Pack
Ruby
297
star
13

active_record_shards

Support for sharded databases and replicas for ActiveRecord
Ruby
246
star
14

delivery_boy

A simple way to publish messages to Kafka from Ruby applications
Ruby
236
star
15

android-db-commons

Some common utilities for ContentProvider/ContentResolver/Cursor and other db-related android stuff
Java
223
star
16

radar

High level API and backend for writing web apps that use push messaging
JavaScript
221
star
17

sunshine-conversations-web

The Smooch Web SDK will add live web messaging to your website or web app.
212
star
18

demo_apps

HTML
179
star
19

arturo

Feature Sliders for Rails
Ruby
174
star
20

belvedere

An image picker library for Android
Java
146
star
21

zendesk_jwt_sso_examples

Examples using JWT for Zendesk SSO
Ruby
141
star
22

sunshine-conversations-ios

Smooch
Objective-C
122
star
23

laika

Log, test, intercept and modify Apollo Client's operations
TypeScript
120
star
24

prop

Puts a cork in their requests
Ruby
117
star
25

zendesk_sdk_ios

Zendesk Mobile SDK for iOS
Objective-C
117
star
26

zopim-chat-web-sdk-sample-app

Zendesk Chat Web SDK sample app developed using React
JavaScript
98
star
27

copenhagen_theme

The default theme for Zendesk Guide
Handlebars
95
star
28

app_scaffold

A scaffold for developers to build ZAF v2 apps
JavaScript
90
star
29

node-publisher

A zero-configuration release automation tool for Node packages inspired by create-react-app and Travis CI.
JavaScript
76
star
30

zendesk_apps_tools

Ruby
75
star
31

zendesk_app_framework_sdk

The Zendesk App Framework (ZAF) SDK is a JavaScript library that simplifies cross-frame communication between iframed apps and the Zendesk App Framework
JavaScript
71
star
32

ios_sdk_demo_apps

This repository contains sample iOS code and applications which use our SDKs
Swift
64
star
33

zendesk_sdk_chat_ios

Mobile Chat SDK for iOS
Objective-C
63
star
34

kamcaptcha

A captcha plugin for Rails
Ruby
63
star
35

linksf

A mobile website to connect those in need in to services that can help them
JavaScript
62
star
36

sdk_demo_app_android

This is Remember The Date, an Android demo app for our Mobile SDK. All docs available on developer.zendesk.com
Java
61
star
37

zcli

A command-line tool for Zendesk
TypeScript
56
star
38

go-httpclerk

A simple HTTP request/response logger for Go supporting multiple formatters.
Go
51
star
39

property_sets

A way to store attributes in a side table.
Ruby
51
star
40

android-schema-utils

Android library for simplifying database schema and migrations management.
Java
48
star
41

android_sdk_demo_apps

This repository contains sample android code and applications which use our SDKs
Java
46
star
42

statsd-logger

StatsD + Datadog APM logging server for development - standalone or embedded
Go
44
star
43

sunshine-conversations-android

Smooch Android SDK
42
star
44

support_sdk_ios

Zendesk Support SDK for iOS
Objective-C
37
star
45

react-native-sunshine-conversations

React Native wrapper for Smooch.io
Java
36
star
46

docker-logs-tail

Docker Logs Tail simultaneously tails logs for all running Docker containers, interleaving them in the command line output
JavaScript
35
star
47

call_center

Ruby
34
star
48

curlybars

Handlebars.js compatible templating library in Ruby
Ruby
34
star
49

kasket

A caching layer for ActiveRecord. Puts a cap on your queries!
Ruby
33
star
50

ruby_memprofiler_pprof

Experimental memory profiler for Ruby that emits pprof files.
C
33
star
51

method_struct

Ruby
33
star
52

samlr

Clean room implementation of SAML for Ruby
Ruby
31
star
53

min-tfs-client

A lightweight python gRPC client to communicate with TensorFlow Serving
C++
31
star
54

sdk_demo_app_ios

This is Remember The Date, an iOS demo app for our Mobile SDK. All docs available on developer.zendesk.com
Objective-C
31
star
55

classic_asp_jwt

A JWT implementation in Classic ASP
ASP
29
star
56

basecrm-ruby

Base CRM API Client
Ruby
29
star
57

volunteer_portal

An event calendar focused on tracking and reporting volunteering opportunities
JavaScript
28
star
58

ultragrep

the grep that greps the hardest.
C
28
star
59

chariot-tooltips

A javascript library for creating on screen step by step tutorials.
JavaScript
26
star
60

clj-headlights

Clojure on Beam
Clojure
26
star
61

sunshine-conversations-javascript

Javascript API for Sunshine Conversations
JavaScript
26
star
62

android-autoprovider

Utility for creating ContentProviders without boilerplate and with heavy customization options.
Java
25
star
63

basecrm-php

Base CRM API client, PHP edition
PHP
23
star
64

migration_tools

Rake tasks for Rails that add groups to migrations
Ruby
23
star
65

large_object_store

Store large objects in memcache or others by slicing them.
Ruby
22
star
66

term-check

A GitHub app which runs checks for flagged terminology in GitHub repos
Go
22
star
67

basecrm-python

BaseCRM API Client for Python
Python
22
star
68

sdk_unity_plugin

This repository contains a unity plugin which wraps the Zendesk support SDKs
Objective-C
22
star
69

jazon

Test assertions on JSONs have never been easier
Java
21
star
70

ipcluster

Node.js master/worker clustering module for sticky session load balancing using IPTABLES
JavaScript
21
star
71

sunshine-conversations-python

Smooch API Library for Python
Python
21
star
72

cloudwatch-logger

Connects standard input to Amazon CloudWatch Logs
Go
20
star
73

forger

Android library for populating the ContentProvider with test data.
Java
19
star
74

radar_client

High level API and backend for writing web apps that use push messaging
JavaScript
19
star
75

double_doc

Write documentation with your code, to keep them in sync, ideal for public API docs.
Ruby
18
star
76

pakkr

Python pipeline utility library
Python
18
star
77

chat_sdk_ios

Zendesk Chat SDK
Objective-C
18
star
78

goship

Utility that helps find, connect and copy to particular cloud resources using configured providers
Go
18
star
79

url_builder_app

A Zendesk App to help you generate links for agents.
JavaScript
18
star
80

sunshine-conversations-api-quickstart-example

Sample code to get started with the Smooch REST APIs
JavaScript
17
star
81

zendesk_apps_support

Ruby
17
star
82

sunshine-conversations-desk

A sample business system built with Meteor and the Smooch API
CSS
17
star
83

apt-s3

apt method for private S3 buckets
Go
17
star
84

api_client

HTTP API Client Builder
Ruby
16
star
85

iron_bank

An opinionated Ruby interface to the Zuora REST API
Ruby
15
star
86

active_record_host_pool

Connect to multiple databases using one ActiveRecord connection
Ruby
15
star
87

private_gem

Keeps your private gems private
Ruby
15
star
88

sdk_messaging_ios

The Zendesk Messaging SDK
Objective-C
14
star
89

rate_my_app_ios

An open source version of the Rate My App feature from 1.x versions of the Support SDK.
Swift
14
star
90

input_sanitizer

A gem to sanitize hash of incoming data
Ruby
14
star
91

sunshine-conversations-conversation-extension-examples

A series of examples using Smooch conversation extensions
HTML
14
star
92

scala-flow

A lightweight library intended to make developing Google DataFlow jobs in Scala easier.
Scala
14
star
93

punchabunch

Punchabunch: A highly concurrent, easily configurable SSH local-forwarding proxy
Go
14
star
94

zendesk-jira-plugin

Java
13
star
95

sunshine-conversations-ruby

Smooch API Library for Ruby
Ruby
13
star
96

samson_secret_puller

kubernetes sidecar and app to publish secrets to a containerized app.
Ruby
13
star
97

sqlitemaster

Android library for getting existing db schema information from sqlite_master table.
Java
13
star
98

ticket_sharing

Ticket Sharing
Ruby
13
star
99

sunshine-conversations-wordpress

PHP
13
star
100

sunshine-conversations-api-spec

Sunshine Conversations OpenAPI Specification for v2+
12
star