PHP function to check if a date is a holiday in Lithuania

Facebooktwitterpinterestlinkedintumblrmail

Here is a simple function for PHP to check if a date, given in standard ISO format (Y-m-d) is a public holiday in Lithuania. I needed one for a project, so here it is for everyone:

 
/**
 * function checks if a passed date is a public holiday 
 * (or weekend) in Lithuania
 * passed values:
 * $weekends - true if you want the function to include weekends
 * default - false
 * $date - 'Y-m-d' format date (or full ISO 8601 datetime string)
 * defaults to current date
 * returns 1 (holiday) or 0 (not a holiday) or error on wrong input
*/
 
function is_lt_holiday(bool $weekends = false, string $date = null): int
{
    //date is today if it was not passed to the function
    if (!isset($date)) $date = date('Y-m-d');
 
    //check if the date is valid
    if (
         strlen($date) < 10 
      || !checkdate(substr($date,5,2), substr($date,8,2), substr($date,0,4))
    ) 
    {
        trigger_error('You shoud pass a valid date in \'Y-m-d\' format');
        return 0; // or should it be null to trigger additional error?
    } 
 
    $year = substr($date,0,4);
    $mday = substr($date,5,5);
    $easter = date('Y-m-d',easter_date($year));
    $easter2 = date('Y-m-d', strtotime($easter . ' +1 day'));
    $public_holidays = [
        '01-01', //new year
        '02-16', //independence day
        '03-11', //restoration of independence day
        substr($easter,5,5), //easter day1
        substr($easter2,5,5), //easter day2
        '05-01', //int worker's day
        '06-24', //summer solstice
        '07-06', //state day
        '08-15', //mary's assumption
        '11-01', //all saints day
        '11-02', //day of the dead
        '12-24', //christmas eve
        '12-25', // christmas day1
        '12-26'  //christmas day2
       ];
 
    if (in_array($mday,$public_holidays)) {
        return 1;
    }
    elseif (
       $weekends == true 
       && (date('D',strtotime($date)) == 'Sat' 
       || date('D',strtotime($date)) == 'Sun')
    ) 
    {
        return 1;
    }
    return 0;
}
 
 
// and now let's test it:
 
echo is_lt_holiday(true);
//today; it depends :)
echo is_lt_holiday(false,'2022-01-01');
//returns 1
echo is_lt_holiday(false,'2022-01-02');
//returns 0
echo is_lt_holiday(false,'2022-01-32');
//returns 0 and error notice - an impossible date
Facebooktwitterpinterestlinkedintumblrmail

2 mintys apie “PHP function to check if a date is a holiday in Lithuania”

  1. Hi Rimas, thanks for suggestions, they make perfect sense. What do you think should be the return value in case of wrong date input?

  2. It would’ve made sense to return a bool instead.

    Also, Easter date checks could have been performed before even splitting the date and checking the whitelist.

Parašykite komentarą

El. pašto adresas nebus skelbiamas.