Search by

blacktools / datetime

henrique.ft

A set of functions to work with date and time in PHP, it contains a powerful schedule maker.

1.0.0 2017-05-30 17:35 UTC

This package is not auto-updated.

Last update: 2026-11-22 13:33:35 UTC


README

A small PHP library for working with dates and times, plus a configurable schedule/calendar renderer.

It provides three main classes:

  • DateMachine — dates in the Y-m-d work format
  • TimeMachine — times in the H:i:s work format
  • Schedule — schedule and calendar tables rendered as HTML or JSON

The library requires PHP 5.4+ and is intentionally written in PHP 5.x-compatible syntax. The test suite requires PHP 8.3+ because it uses Pest 4.

Documentation

A standalone, offline-friendly HTML documentation site is included in docs/.

Open docs/index.html directly, or serve it locally:

php -S 127.0.0.1:8000 -t docs

Then visit http://127.0.0.1:8000/.

Installation

Install with Composer:

composer require blacktools/datetime

Then include the Composer autoloader:

require 'vendor/autoload.php';

PHP version requirements

The runtime requires PHP 5.4+. The source intentionally uses PHP 5.x-compatible syntax, including short array syntax, and avoids language features introduced in PHP 7 or PHP 8.

For development and tests:

  • PHP 8.3+
  • Composer

DateMachine

DateMachine works with dates in the internal work format:

Y-m-d    →    2024-01-31

The display format is configurable.

Configuration

use Blacktools\DateTime\DateMachine;

$date = new DateMachine([
    'show_format' => 'd/m/Y',
    'language' => 'EN',
    'timezone' => 'America/Sao_Paulo',
]);

Available settings:

Option Default Description
show_format Y-m-d Display format used by isShow(), toShow() and toWork()
language EN Weekday language: EN, PT, or ES
timezone America/Sao_Paulo Timezone applied with date_default_timezone_set()

Unknown settings are ignored.

Show/work date conversion

$date = new DateMachine(['show_format' => 'd/m/Y']);

$date->isWork('2024-01-31');   // true  — expects Y-m-d
$date->isWork('31/01/2024');   // false

$date->isShow('31/01/2024');   // true  — expects the configured show format
$date->isShow('2024-01-31');   // false

$date->toShow('2024-01-31');   // '31/01/2024'
$date->toWork('31/01/2024');   // '2024-01-31'

Static formatting

use Blacktools\DateTime\DateMachine;

DateMachine::format('31/01/2024', 'd/m/Y', 'Y-m-d');
// '2024-01-31'

Validation

DateMachine::validate('2024-01-31'); // true
DateMachine::validate('2024-01-32'); // false
DateMachine::validate('not-a-date'); // false

Adding and subtracting days

addDays() includes the start date in the returned range:

DateMachine::addDays('2024-01-01', 3);
// [
//   '2024-01-01',
//   '2024-01-02',
//   '2024-01-03',
//   '2024-01-04',
// ]

DateMachine::addDays('2024-01-01', 3, false);
// '2024-01-04'

subDays() returns the previous days plus the start date, in chronological order:

DateMachine::subDays('2024-01-10', 3);
// [
//   '2024-01-07',
//   '2024-01-08',
//   '2024-01-09',
//   '2024-01-10',
// ]

DateMachine::subDays('2024-01-10', 3, false);
// '2024-01-07'

Both methods use 7 days by default.

Current limitation: addDays() does not support negative day counts yet. Use subDays() for subtraction.

Date ranges

DateMachine::interval('2024-01-01', '2024-01-03');
// [
//   '2024-01-01',
//   '2024-01-02',
//   '2024-01-03',
// ]

The range is inclusive. A reversed range returns an empty array.

Weekdays

use Blacktools\DateTime\DateMachine;

$date = new DateMachine(['language' => 'EN']);

$date->weekDay('2024-01-01');
// '1'

$date->weekDay('2024-01-01', 'name');
// 'Monday'

$date->weekDaysBetween('2024-01-01', '2024-01-03', 'name');
// ['Monday', 'Tuesday', 'Wednesday']

$date->weekDaysBetween('2024-01-01', '2024-01-03', 'numeric');
// ['1', '2', '3']

Weekday numbering follows PHP's date('w'):

Number Day
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday

Previous weekday search

DateMachine::getUntilWeekDayBefore('2024-01-10', 3);
// ['2024-01-03', ..., '2024-01-10']

Returns the dates from the previous requested weekday through the start date.

Current-month helpers

DateMachine::getFirstDateOfCurrentMonth();
// e.g. '2026-11-1'

DateMachine::getFirstWeekDayOfCurrentMonth();
// weekday number of the first day of the current month

The day in getFirstDateOfCurrentMonth() is not zero-padded.

DateMachine error behavior

Invalid conversions return null and echo a styled error block when PHP error reporting is enabled. Boolean validators return false.

TimeMachine

TimeMachine works with times in the internal work format:

H:i:s    →    13:05:09

Configuration

use Blacktools\DateTime\TimeMachine;

$time = new TimeMachine([
    'show_format' => 'H:i',
]);
Option Default Description
show_format H:i:s Display format used by isShow(), toShow() and toWork()

Unknown settings are ignored.

Show/work time conversion

$time = new TimeMachine(['show_format' => 'H:i']);

$time->isWork('13:05:09'); // true
$time->isWork('13:05');    // false

$time->isShow('13:05');    // true
$time->isShow('13:05:09'); // false

$time->toShow('13:05:09'); // '13:05'
$time->toWork('13:05');    // '13:05:00'

Static formatting

TimeMachine::format('13:05:09', 'H:i:s', 'H:i');
// '13:05'

Validation

TimeMachine::validate('00:00:00'); // true
TimeMachine::validate('23:59:59'); // true
TimeMachine::validate('24:00:00'); // false
TimeMachine::validate('23:60:00'); // false

Comparison

Supported comparison operators:

>   <   ==   >=   <=   !=
TimeMachine::compare('12:00:00', '10:00:00', '>');  // true
TimeMachine::compare('10:00:00', '12:00:00', '<');  // true
TimeMachine::compare('10:00:00', '10:00:00', '=='); // true
TimeMachine::compare('10:00:00', '10:00:00', '!='); // false

The default comparison is ==.

Intervals

TimeMachine::interval('10:00:00', '12:00:00');
// ['10:00:00', '11:00:00', '12:00:00']

TimeMachine::interval('10:00:00', '12:00:00', '01:30:00');
// ['10:00:00', '11:30:00', '13:00:00']

The start time is always included. The loop adds the interval until the current time is no longer before the end, so a step can go beyond the end time.

A full-day interval should end at 23:59:59:

TimeMachine::interval('00:00:00', '23:59:59');
// 24 entries: 00:00:00 through 23:00:00

Current limitation: 24:00:00 is rejected by validate(), so interval('00:00:00', '24:00:00') returns null.

Interval with display values

intervalShow() is an instance method and returns both work and display values:

$time = new TimeMachine(['show_format' => 'H:i']);

$time->intervalShow('10:00:00', '11:00:00');
// [
//   ['show' => '10:00', 'work' => '10:00:00'],
//   ['show' => '11:00', 'work' => '11:00:00'],
// ]

Difference

TimeMachine::diff('12:00:00', '10:30:00');
// '01:30:00'

TimeMachine::diff('10:00:00', '10:00:00');
// '00:00:00'

The first time must be later than or equal to the second time.

Summing times

sum() accepts between 2 and 24 time values:

TimeMachine::sum('12:30:45', '01:20:20');
// '13:51:05'

TimeMachine::sum('11:00:00', '12:00:00');
// '23:00:00'

TimeMachine::sum('12:00:00', '12:00:00');
// '00:00:00' — wraps at 24 hours

Current limitation

TimeMachine::toSeconds() currently throws an error for valid time strings. Avoid it until the known issue is fixed.

Schedule

Schedule creates a table of dates, weekdays, and hours, with support for schedule modes and calendar-style month grids.

Basic usage

use Blacktools\DateTime\Schedule;

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-07',
    'start_hour' => '08:00:00',
    'end_hour' => '18:00:00',
    'hour_interval' => '01:00:00',
    'language' => 'PT',
    'work_by' => 'all',
]);

echo $schedule->getHtml();

Configuration options

Option Default Description
table_attributes '' Attributes for <table>
thead_attributes '' Attributes for <thead>
tbody_attributes '' Attributes for <tbody>
caption_content '' Caption text; rendered only when non-empty
caption_attributes '' Attributes for <caption>
hours_attributes '' Attributes for hour-label cells
week_days_attributes '' Attributes for weekday header rows
month_days_attributes '' Attributes for date header rows
show_date_format Y-m-d Date format for headers
show_time_format H:i:s Time format for hour labels
show_hour_interval true Adds the half-hour value under each hour label
start_date today First schedule date
end_date today + 20 days Last schedule date
show_week_days true Show the weekday header row
show_month_days true Show the date header row
language PT Weekday language: PT, EN, or ES
start_hour 00:00:00 First hour row
end_hour 23:59:59 Last hour row
work_by all all, week_day, month_day, or calendar
calendar_start_week_day_number 1 First weekday of a calendar week
hour_interval 01:00:00 Step between hour rows

Pass boolean values for show_week_days and show_month_days to avoid the strict-comparison behavior described in the limitations section.

Work modes

all (default)

Cells are indexed by date → weekday → hour.

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-03',
    'start_hour' => '08:00:00',
    'end_hour' => '18:00:00',
    'work_by' => 'all',
]);

Fill a cell:

$schedule->fill([
    '2024-01-01' => [
        '1' => [
            '08:00:00' => [
                'content' => 'Meeting',
                'attributes' => 'class="busy"',
            ],
        ],
    ],
]);

week_day

Cells are indexed by weekday → hour.

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-07',
    'work_by' => 'week_day',
]);

$schedule->fill([
    '1' => [
        '08:00:00' => ['content' => 'Monday meeting'],
    ],
]);

month_day

Cells are indexed by date → hour.

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'work_by' => 'month_day',
]);

$schedule->fill([
    '2024-01-15' => [
        '08:00:00' => ['content' => 'Event'],
    ],
]);

calendar

Calendar mode renders a month-style grid. Cells are indexed by date → weekday number and contain the day number by default.

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'work_by' => 'calendar',
    'language' => 'PT',
]);

echo $schedule->getHtml();

Fill a calendar day:

$schedule->fill([
    '2024-01-15' => [
        '1' => ['content' => 'Holiday', 'attributes' => 'class="holiday"'],
    ],
]);

Days before the start date are rendered as excluded cells.

Filling cells

fill() recursively merges into existing cells:

$schedule->fill([
    '2024-01-01' => [
        '1' => [
            '08:00:00' => [
                'content' => 'Meeting',
                'attributes' => 'class="busy"',
            ],
        ],
    ],
]);

Notes:

  • Only existing top-level date/weekday keys are merged.
  • Nested keys can be added under an existing top-level key.
  • Filling another cell preserves the remaining cells.
  • Calling config() again regenerates cells and discards previously filled content.

HTML output

$html = $schedule->getHtml();

JSON output

$json = $schedule->getJson();

$cells = json_decode($json, true);

Debug output

debug() returns a <table> string that displays the internal cell keys:

echo $schedule->debug();

This is useful for checking which keys to pass to fill().

Accessing internals

The following properties are readable:

$schedule->date;
$schedule->time;
$schedule->dates;
$schedule->week_days;
$schedule->week_days_numeric;
$schedule->hours;
$schedule->cells;
$schedule->config;
$schedule->calendar_week_days_excluded;

Example:

print_r($schedule->cells);

Reconfiguring

$schedule = new Schedule([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-07',
]);

$schedule->config([
    'start_date' => '2024-02-01',
    'end_date' => '2024-02-07',
    'language' => 'EN',
]);

Error handling

The library does not currently throw exceptions for normal usage errors. Instead:

  • Validators return false
  • Conversions return null
  • Methods echo a styled <pre> error block when error_reporting() !== 0
  • Invalid configuration passed to a constructor may call die()

If you need to suppress the rendered error output:

error_reporting(0);

For new applications, prefer validating input and checking return values before using results.

Known limitations

These are current behaviors, preserved for backward compatibility:

  • DateMachine::addDays() does not support negative values; use subDays().
  • DateMachine::validate() accepts normalized impossible dates such as 2024-02-30.
  • DateMachine::weekDaysBetween() returns null when called without dates.
  • TimeMachine::toSeconds() throws for valid input.
  • TimeMachine::validate('24:00:00') returns false.
  • TimeMachine::interval() can include a step beyond the end time.
  • Calendar mode ignores a custom Sunday start when start_date is a Monday.
  • show_month_days and show_week_days use strict boolean comparisons internally; pass true or false.
  • Invalid calendar input can produce fatal errors before a friendly error block is displayed.

Development

Install dependencies:

composer install

Run the tests:

composer test

Run the code style check:

composer lint

Apply code style fixes:

composer lint:fix

The test suite uses Pest and includes current-behavior tests plus rendering regression fixtures.

Legacy example

The original manual example lives in:

legacy/src.php

Run it from the legacy/ directory:

cd legacy
php src.php

Contributing

Pull requests and issues are welcome.

Security

If you discover a security issue, please email hriqueft@gmail.com instead of using the public issue tracker.

License

The MIT License. See LICENSE.