Search by

arraypress / wp-date-utils

arraypress

Dates for reporting: UTC ranges, presets, chart buckets and relative phrasing, plus the site timezone and formats.

Package info

github.com/arraypress/wp-date-utils

pkg:composer/arraypress/wp-date-utils

Statistics

Installs: 654

Dependents: 2

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-08-25 18:02 UTC

This package is auto-updated.

Last update: 2026-11-18 10:51:10 UTC


README

This library has moved. It is now part of sugarcommerce/dates (namespace SugarCommerce\Dates, PHP 8.3+). That package's README has a "Moving from arraypress/wp-*" table. This repository is archived and read-only.

WP Dates

Date ranges for reporting: presets, UTC boundaries, chart buckets and the site's own clock.

What it does

A reports screen needs the same handful of things every time — what "last 30 days" means in UTC, the equivalent window before it to compare against, the buckets to plot, and the site's timezone and format for showing a date back.

Getting that right by hand means remembering that WordPress stores UTC and displays local, that a range is half-open or a row lands in two months at once, and that "3 days ago" needs the exact date in a tooltip. This does all of it in one place.

Features

  • Turn a preset — this month, last quarter — into a start and end in UTC
  • Get the matching period before it, for a comparison figure
  • Build the WHERE clause and its bound parameters from a range
  • Bucket a range by hour, day, week, month, quarter or year for a chart, in the site's timezone (Buckets)
  • Resolve a preset in a timezone, with the week starting on the site's day
  • Show a date in the site's timezone and the site's format
  • Say "3 days ago" with the exact date available underneath, translated, counted the library's way or WordPress's
  • Say a run of days as shortly as it can be said (Site::span())
  • Read a typed date strictly, and the last second of one (Timestamp::from_date(), ::end_of_day())
  • Take a period from an API client or an assistant: a JSON Schema and a strict reader (Preset::input_schema(), ::parse_input())
  • Freeze the clock in tests, so a date-dependent assertion is not flaky
  • Turn a DateTime, a Unix timestamp or a string into the UTC datetime to store (Timestamp::to_sql()), and tell an empty or zero date from a real one (Timestamp::is_empty())

Installation

composer require arraypress/wp-date-utils

Quick start

The window a report is showing, and the one before it:

use ArrayPress\Dates\Preset;

$range    = Preset::Last30Days->range();
$previous = $range->previous();

// 2026-07-27 00:00:00 to 2026-08-26 00:00:00, in UTC.
// where_prepared() writes %s placeholders for $wpdb; where() writes :from
// and :to for PDO.
[ $where, $params ] = $range->where_prepared( 'date_created' );

$sales = $wpdb->get_var(
	$wpdb->prepare( "SELECT SUM(total) FROM {$table} WHERE {$where}", $params )
);

Preset::options() gives the whole list, labelled, for a dropdown.

Whose midnight

A period is two UTC moments, but "today" is somebody's day. Left alone the days are UTC's. Pass a timezone, and the day its week starts on, and every boundary is that zone's midnight — a day the clocks change is 23 or 25 hours long — while the range still prints UTC for the query:

$today = Preset::Today->range( null, wp_timezone(), (int) get_option( 'start_of_week', 1 ) );

// For a shop in New York in July: 04:00:00 UTC to 04:00:00 UTC the next day.
[ $where, $params ] = $today->where_prepared( 'date_created' );

// A preset slug, or two dates somebody picked, the same way.
$range = Preset::resolve( $slug, $from, $to, null, wp_timezone(), 0 );

// The last seven whole days, today included.
$week = Range::last_days( 7, null, wp_timezone() );

Buckets for a chart

Buckets cuts a range into the pieces a chart draws, in the site's timezone: hours for a day, days for a fortnight, numbered weeks for a month, then months, quarters and years. Weeks start on the site's first day of the week, the hour the clocks go back is on the axis once, and the names come through wp_date(), so they are translated.

use ArrayPress\Dates\Buckets;

$buckets = Buckets::for_range( $range );   // size, keys, labels, titles, starts
$index   = array_flip( $buckets['keys'] );

// Rows grouped by the hour of the stored UTC value -- the same SQL on MySQL,
// MariaDB and SQLite -- and turned into the site's hours here.
$length = Buckets::slot_length( $range );  // 13, or 16 for a zone off the hour

foreach ( $rows as $row ) {  // SELECT SUBSTR( date_created, 1, {$length} ) AS slot, ...
	$at = $index[ Buckets::key( Buckets::slot_time( $row->slot ), $buckets['size'] ) ] ?? null;
}

Interval is the other way to group, in SQL and in UTC: $range->series_query() with $range->fill(). A quarter there is keyed by its first month (2026-04), and from 2.1.0 the SQL groups by that too — before, the second and third months of each quarter were lost between the query and fill().

Showing a stored UTC date back to somebody:

use ArrayPress\Dates\Site;

echo Site::format( $order->date_created );              // in the site's timezone and format
echo Site::format_datetime( $order->date_created );     // the date and the time
echo Site::relative_html( $order->date_created );       // <span title="the exact moment">3 days ago</span>
echo Site::span( $range->start(), $last_day );          // "9–15 Nov 2026", "30 Nov – 6 Dec 2026"
echo Site::duration( time() - $started );               // "3 months"

Site::format() goes through wp_date(), so month and day names are the site's language and T or P in a format name the site's zone.

Relative time

Site::relative() and Site::duration() pick a whole translated phrase for each unit and count (_n(), text domain arraypress), because "3 weeks ago" cannot be translated as "%s ago" round somebody else's "3 weeks". By default they count whole units ("1 week" until a second has passed), say "just now" under a minute, and give a date in place of anything more than thirty days off. WordPress's human_time_diff() counts to the nearest unit and never gives a date, and a screen that has always used it can keep its wording:

Site::relative( $value );                             // "1 week ago" at 13 days; "14 Jun 2026" at 31
Site::relative( $value, null, Site::LIKE_WORDPRESS ); // "2 weeks ago" at 13 days; "1 month ago" at 31
Site::relative( $value, null, array( 'cutoff' => 0, 'just_now' => false ) );

The options are cutoff, fallback, round, just_now and abbreviate. Relative::parts( $seconds ) gives the unit and the count without the words.

A period asked for by API

A REST route or an Abilities API ability that reports on a period takes the same three inputs: a named period, or a start and an end of the caller's own. input_schema() describes them and parse_input() reads them -- strictly, because a client that asked for the wrong thing should be told, where resolve() quietly falls back for a person at a screen.

use ArrayPress\Dates\Preset;

// The route's args, or the ability's input properties.
$args = Preset::input_schema( Preset::Last30Days ) + $my_other_args;

// In the callback.
$asked = Preset::parse_input( $request->get_params(), Preset::Last30Days, 'myplugin' );

if ( is_wp_error( $asked ) ) {
    return $asked; // myplugin_bad_period or myplugin_bad_date, status 400
}

// [ 'preset' => 'last_30', 'start' => '', 'end' => '' ]
// or [ 'preset' => 'custom', 'start' => '2026-05-01', 'end' => '2026-05-31' ]
$range = Preset::resolve( $asked['preset'], $asked['start'], $asked['end'], null, wp_timezone() );
Asked for Answer
nothing the fallback
period that is a slug (any case) that preset
start and end, real YYYY-MM-DD days, start not after end custom with the two dates; the whole end day is counted
an unknown period, or a period with dates {prefix}_bad_period
one date alone, a date that is not a real day, or a start after the end {prefix}_bad_date

Pass your own wording for any of the three descriptions as the second argument of input_schema().

Dates somebody typed

Timestamp::parse() is lenient — it reads tomorrow — and is for stored values. A date from a form goes through the strict pair, which answer null for anything that is not a real day (2026-02-30, 2026-7-5, next friday):

$starts = Timestamp::from_date( $_POST['start'] );                 // midnight UTC, as Unix time
$ends   = Timestamp::end_of_day( $_POST['end'], 'Europe/Dublin' ); // the last second of that day there

$stored = null === $ends ? Timestamp::ZERO : Timestamp::at( $ends );

// Or in one step, for a date input on its way into a datetime column:
$stored = Timestamp::date_to_sql( $_POST['end'], 'end' ); // '2026-07-15 23:59:59', or the zero date

The zero date in any spelling — 0000-00-00, with a time, with fractions of a second — is no date: parse(), to_unix() and to_sql() answer null, format() an empty string and is_past() false. A string with no zone on it is read as UTC whatever date_default_timezone_set() was last given. Timestamp::format_localized( $unix, 'de-DE' ) writes a date the way a language other than the site's does ("15. Juli 2026"), with ext-intl.

Requirements

  • PHP 8.3 or later
  • WordPress 7.1 or later

License

GPL-2.0-or-later