Giter Site home page Giter Site logo

date-holidays-parser's Introduction

date-holidays-parser

parser for world-wide holidays

NPM version Build Status

This module provides a parser for date-holidays which does calculation of holidays dates for various countries, states and regions by type while considering the applicable timezone.

The features are:

  • calculation of public, bank and observance holidays for different countries, state, region, following ISO 3166-2
  • consideration of timezones for holiday checks
  • consideration of start and end time dependent on timezone
  • substitute days
  • multi-language support for all holiday names
  • setting of custom holidays
  • uses own grammar for calculation of days
  • support for islamic calendar from 1970 to 2080 (*islamic dates might not be correct as they are subject to the sighting of the moon)
  • support for hebrew calendar from 1970 to 2100
  • support for chinese calendar

Happy holidays!

Table of Contents

Usage

const data = require('date-holidays/data/holidays.json')
const Holidays = require('date-holidays-parser')
const hd = new Holidays(data)

// get supported countries
hd.getCountries()
/*>
{ AD: 'Andorra',
  ...
  US: 'United States' }
*/

// get supported states e.g. for US
hd.getStates('US')
/*>
{ al: 'Alabama',
  ...
  wy: 'Wyoming' }
*/

// get supported regions e.g. for US, Lousiana
hd.getRegions('US', 'la')
/*>
{ no: 'New Orleans' }
*/

// initialize holidays for US, Lousiana, New Orleans
hd.init('US', 'la', 'no')
// or using a new instance
hd = new Holidays('US', 'la', 'no')

// get all holidays for the year 2016
hd.getHolidays(2016)
/*>
[ { date: '2016-01-01 00:00:00',
    start: Fri Jan 01 2016 00:00:00 GMT-0600 (CST),
    end: Sat Jan 02 2016 00:00:00 GMT-0600 (CST),
    name: 'New Year\'s Day',
    type: 'public' },
  ...
  { date: '2016-11-24 00:00:00',
    start: Thu Nov 24 2016 00:00:00 GMT-0600 (CST),
    end: Fri Nov 25 2016 00:00:00 GMT-0600 (CST),
    name: 'Thanksgiving Day',
    type: 'public' },
  ...
  { date: '2016-12-26 00:00:00',
    start: Mon Dec 26 2016 00:00:00 GMT-0600 (CST),
    end: Tue Dec 27 2016 00:00:00 GMT-0600 (CST),
    substitute: true,
    name: 'Christmas Day (substitute day)',
    type: 'public' } ]
*/

// check if date is a holiday while respecting timezones
hd.isHoliday(new Date('2016-02-09 00:00:00 GMT+0000'))
//> false
hd.isHoliday(new Date('2016-02-09 10:00:00 GMT-0600'))
/*>
{ date: '2016-02-09 00:00:00',
  start: Tue Feb 09 2016 00:00:00 GMT-0600 (CST),
  end: Wed Feb 10 2016 00:00:00 GMT-0600 (CST),
  name: 'Mardi Gras',
  type: 'public' }
*/

Holiday object

getHolidays() as well as a matching isHoliday() call return either a list or a single holiday object which consists of:

  • {String} date - ISO Date String of (start)-date in local format
  • {Date} start - start date of holiday
  • {Date} end - end date of holiday
  • {String} name - name of holiday using language (if available)
  • {String} type - type of holiday public|bank|school|optional|observance
  • {Boolean} substitute - (optional) if true holiday substitutes another holiday`
  • {String} note - (optional) note`

Dates

The date String represents the start date of the holiday in ISO format without timezone. This string it intended for information only.

start and end are the start/end date of the holiday within the selected timezone of the country, state, region.

Name

The name names the holiday in the local language of the selected country, state, region. The applied language(s) can be requested using getLanguages().

The language can be changed using the setLanguages() method. In case that not translation is available a fall-back to the next given language will be made. E.g. local language is "fr", setLanguages('nl') was called. For all holidays where no dutch translation is available the French version will be used instead.

All holiday names should support an English translation.

Types of holidays

Currently the following type with their meaning are supported

type meaning
public public holiday
bank bank holiday, banks and offices are closed
school school holiday, schools are closed
optional majority of people take a day off
observance optional festivity, no paid day off

Additionally a note field is sometimes available for further clarification.

API

See Holidays API for further information.

Browser

This project also runs in all modern browsers. See ./examples/browser

Browser Version Notes
Chrome >=45
Firefox >=45
Safari >=10
Edge >=13
IE >=10 needs polyfill core-js/es6

Please do not forget to set the correct charset!

<html>
<head>
  <!-- set page-wide -->
  <meta charset="UTF-8">
  ...
</head>
<body>
  ...
  <!-- or per script -->
  <script src="your-bundle.js" charset="UTF-8"></script>

Testing was done with zuul. For local browser tests run npm run zuul -- --local 3000 and open http://localhost:3000/__zuul.

requires manual install of

npm i zuul@3 browserify@10

Data

All data for the holidays of the different countries is contained in ./data/holidays.json. For changing holiday data edit the appropriate country in ./data/countries. Any details on structure and available grammar for holiday attribution is described in holidays.yaml specification.

Contribution and License Agreement

If you contribute code to this project, you are implicitly allowing your code to be distributed under the ISC license. You are also implicitly verifying that all code is your original work or correctly attributed with the source of its origin and license.

License

Copyright (c) 2015-present commenthol (ISC License)

See LICENSE for more information.

References

date-holidays-parser's People

Contributors

0xflotus avatar commenthol avatar davidan90 avatar leipert avatar leonidasv avatar myas92 avatar oprogramador avatar schinnerl-at avatar simplymequeeny avatar stefanvanherwijnen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

date-holidays-parser's Issues

set Day Off

Hi there,

hd.getDayOff() returns undefined (country 'CH', 'GE'))

setDayOff() does not exist, and can't find any documentation related. Can you help me ?

Thanks

Must use import to load ES Module

Hello,

I'm using date-holidays in a Vtex.IO project.

Here I can only use import and not require.

However, I am getting this error when trying to use the lib.

Captura de Tela 2021-08-11 às 11 57 13

Any way to solve?

Weekday spelling in rules is in lowercase only

Currently all weekdays for parsing rules need to be typed in lower case. This might lead to confusions.
This should be possible to write weekdays correctly being the first letter in uppercase.
The Parser should detect weekdays correctly e.g. Monday, ..., Sunday within the rules.
Current rules should not be affected by such change.

parsing PT12H truncates end at midnight - is this desired behaviour?

can I please check in order to understand this library - it contains a test with the code:

    it('02-06 and if saturday then previous friday if sunday then next monday in 2016', function () {
      const fn = new DateFn('02-06 14:00 and if saturday then previous friday 16:45 if sunday then next monday PT12H')
      const res = fn.inYear(2016).get()
      const exp = [{
        date: '2016-02-06 14:00:00',
        start: 'sat 2016-02-06 14:00',
        end: 'sun 2016-02-07 00:00'
      }, {
        date: '2016-02-05 16:45:00',
        start: 'fri 2016-02-05 16:45',
        end: 'sat 2016-02-06 00:00',
        substitute: true
      }]
      assert.deepStrictEqual(fixResult(res), exp)
    })

my take on PT12H would be a timespan/duration of 12 hours, in which case the expected end dates should be 'sun 2016-02-07 02:00' and 'sat 2016-02-06 04:45' respectively. Is this test set up correctly?

Custom holiday list

My company's business logic requires me to filter for only major holidays and a few local city holidays.
I've tried filtering the array from hd.getHolidays() and then setting the new filtered array of holidays but i'm still getting all of the holidays.

Is there a way to overwrite the current holiday array?

Get holidays for a subset (or all) the available countries

Hi.
First of all, thanks for this work, is amazing!

As part of discovering holidays data sources, I found this project. One of my uses cases would be to query all the holidays for a list of countries. Looking at the API docs, I found that the init method receives a Country instance. Is there a way to extend this to receive a list of countries? I guess one approach could be having a list of Holidays instances but a) Not sure how this would perform and 2) It would be cleaner to leave that to the module instead.

Any guidance on this would be appreciated.

Compile to es5 for the published version

When trying to use this module with webpack and uglify it fails due to es6 features.

See webpack/webpack#5682 (comment)

Ideally there should be a prepublish script to compile the code to es5 so that it can be used with webpack without having to be specifically targeted for compilation.

I'd be happy to do up a PR for this if you want.

I am getting both the holiday AND the substitute day

Hi, I might be missing something.

Jan 1st, 2022 is Saturday. The rule is "01-01 and if saturday,sunday then next monday" so the holiday is actually on Jan 3rd.

However, the following code returns BOTH the Saturday AND the Monday as items 0 and 1 in the hols array and the isHoliday(hols[0].start) returns Jan 1st as being the holiday.

const holsObj = new Holidays('AU', 'NSW')
const hols = holsObj.getHolidays('2022')
const isHol = holsObj.isHoliday(hols[0].start) 

Using year 2025, where Jan 1st on Wednesday, it only returns the one date, as expected.

Is there a way to get the actual holiday applicable in that year?

Thanks for a great library,
Murray

Error: this._shorten is not a function

Hi here,

I'm trying to use date-holidays in my angular 7 project with typescript.
I meet an issue when I intialize new Holidays('US', 'la', 'no') (for exemple) :

image

image

It seems that the problem occurs when the country is made of 2 characters, I have the same problem with new Holidays('Fr'), but when i'm doing new Holidays('France') the result is :

image

Beside, when I use something like
image
it works fine.

My import is made as follow:
image

I think that there is something wrong with my init but i don't understand what.. I'm pretty new in the web development !
Thanks !

Export typescript definitions

The library is not usable with Typescript at the moment.

Include

"exports": {
    // ...
    "types": "./types"
}

in the package.json, since right now the types are not exported and not usable. All the types in thy types directory are duplicated in the dates-holidays library for some reason and exported there. However, if one wants to use just the parser itself, types are not exported at all.

Problem with date in different timezone (UTC Offset)

Hello,

We have a timezone system based in different customers within the same codebase. Each customer has its timezone set against itself and we use it together with moment-timezone to deal with their correct and exact time and days (start of, end of and exactly time for each time).

The issue happens when the holiday and the timezone offsets the zulu time per one day, e.g.:

  • checking if 01-01-2018 is a holiday
  • in australia timezone this day is 2017-12-31T13:00:00.000Z
  • when using hd.isHoliday it uses const year = toYear(date); which returns 2017
  • thus, it gets the holidays set from 2017 which ends up in not being a holiday, once there is no data where the given date is => startDate or < endDate (according from the excerpt of the code)
if (hd[j] && date >= hd[j].start && date < hd[j].end)

In other words, given:

const hd = new Holidays('AU');
const holiday = hd.isHoliday(new Date("2017-12-31T13:00:00.000Z"));

holiday should be

{ 
  date: '2018-01-01 00:00:00',
  start: 2017-12-31T13:00:00.000Z,
  end: 2018-01-01T13:00:00.000Z,
  name: "New Year's Day",
  type: 'public' 
}

However it's returning that this is not a holiday.

How to make the lib more lightweight ?

I need to reduce the lib size (1.1MB) and I would like to know if there is a way to make it more lightweight ?

Capture d’écran 2022-09-22 à 10 18 02

From this issue, I tried using date-holiday-parser (instead of date-holiday) with a custom json data but it made any improvement (still 1.1MB).

// date.utils.ts
import Holidays from 'date-holidays-parser';

const customHolidayJsonData = {
	holidays: {
		FR: {
			names: {
				fr: 'France',
				en: 'France',
			},
			dayoff: 'sunday',
			zones: ['Europe/Paris'],
			langs: ['fr'],
			days: {
				'01-01': {
					_name: '01-01',
				},
			},
		},
	},
	names: {
		'01-01': {
			name: {
				en: "New Year's Day",
				fr: 'Nouvel An',
			},
		},
	},
};

const holiday = new Holidays(customHolidayJsonData);
holiday.init('FR');

Is there a way of improvement / am I doing something wrong ?

TypeError After UnsetRule

Hello,
I want to ignore a holiday by using unsetRule. The holiday does not appear in the list returned by getHolidays however when checking for that date using isHoliday I get the following Typerror

const hd = new Holidays();
hd.init('GR', { types: ['public'] });
hd.isHoliday('2023-04-14'); //returns true
hd.unsetRule('orthodox -2'); //returns true
hd.isHoliday('2023-04-14'); // => throws error
Uncaught TypeError: Cannot read property 'inYear' of undefined
    at Holidays.isHoliday (node_modules/date-holidays-parser/lib/Holidays.cjs:220:33)
    at Holidays._dateByRule (node_modules/date-holidays-parser/lib/Holidays.cjs:396:28)

Add new rule "<date> on weekday"

Add a new rule which allows to set a holiday only if falling on certain weekday(s).
Rule is required for Swiss holiday 12-26 "Stefanstag" which is a holiday in some Cantones if not on Friday or Monday.

Proposal: New rule for attribution of active/ inactive holidays

A holiday name may change over time and get replaced or discontinued.
The same applies if a holiday is effective from a certain timestamp on.
Currently this is attributed by the active array using {to, from}.
For renaming a name this then will case a duplication of the rule name which then is resolved with a numbering scheme using #1.
This is not ideal.

It is therefore proposed to introduce a set of new rules:

<rule> since YYYY(-MM-DD)?

means that the rule is effective since year

<rule> prior to YYYY(-MM-DD)?

means that the rule is effective prior to year

<rule> since YYYY(-MM-DD)? and prior to YYYY(-MM-DD)?

means that the rule is effective since year and prior to another year

Including in Angular causing commonjs warnings

Can the project be updated to support Es2020, or at least ES2015 so packaging of the code can take advantage of tree shaking.

You get warning like this atm

image

My tsconfig file looks like so

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "../../out-tsc/app",
    "types": [],
    "module": "esnext",
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

My route tsconfig looks like so

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

Data?

I'm getting 404 on the link to holiday data. Is there any existing database?

o.str.substr is not a function

Error:

Exception while invoking method 'getHolidays' TypeError: o.str.substr is not a function
     at Parser._shorten (/app/node_modules/date-holidays-parser/lib/Parser.js:192:21)

with the country 'AT':

const Holidays = require('date-holidays');
let holidays = new Holidays();
holidays.init('AT');
holidays.getHolidays(2020); // ERROR

After some debugging:

    key: "_shorten",
    value: function _shorten(o, cap0) {
      console.log({ o, cap0 });
      o.str = o.str.substr(cap0.length, o.str.length);
    }

it seems like that o and cap0 are both functions!!

Please fix, this is very annoying as this completely breaks the whole library for me 😢

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.