The DateTimeHelper class is a static utility for all date and time work: formatting, timezone conversion, arithmetic, comparisons, and human-readable output. All methods are static, so you can call them directly or via $app->dateTime.
- Class:
JiFramework\Core\Utilities\DateTimeHelper - Access:
$app->dateTime(lazy-loaded instance) - All methods are static —
DateTimeHelper::now()and$app->dateTime->now()are equivalent - Default format:
'Y-m-d H:i:s'— MySQL-compatible, available as the constantDateTimeHelper::DB_FORMAT - Timezone: reads
Config::$timezonefromjiconfig.php. Methods that accept a$timezoneparameter can override it per call.
use JiFramework\Core\Utilities\DateTimeHelper;
echo DateTimeHelper::now(); // '2024-06-15 14:30:00'
echo DateTimeHelper::addDays('2024-06-15', 10, 'Y-m-d'); // '2024-06-25'
DateTimeHelper::isPast('2020-01-01 00:00:00'); // true
DateTimeHelper::isToday(DateTimeHelper::now()); // true
echo DateTimeHelper::getTimeElapsedString('2024-01-01 10:00:00'); // '5 months ago'
static getAppTimezone(): string
Return the application's configured timezone identifier. Falls back to the PHP system default (date_default_timezone_get()) when Config::$timezone is empty.
Returns: string — a valid timezone identifier, e.g. 'Asia/Dhaka', 'UTC'.
echo DateTimeHelper::getAppTimezone(); // 'Asia/Dhaka' (from jiconfig.php)
static isValidTimezone(string $timezone): bool
Check whether a timezone identifier is valid by testing it against PHP's full list of supported identifiers.
$timezone— (string) Timezone identifier to test, e.g.'Asia/Dhaka'.
Returns: bool — true if the identifier is recognised by PHP.
DateTimeHelper::isValidTimezone('Asia/Dhaka'); // true
DateTimeHelper::isValidTimezone('UTC'); // true
DateTimeHelper::isValidTimezone('Invalid/Zone'); // false
static getSupportedTimezones(): array
Return all timezone identifiers supported by PHP (delegates to DateTimeZone::listIdentifiers()).
Returns: string[] — list of all valid timezone identifier strings.
$timezones = DateTimeHelper::getSupportedTimezones();
// ['Africa/Abidjan', 'Africa/Accra', ... 'UTC', ... 'Pacific/Auckland']
// Validate a user-submitted timezone
$tz = $_POST['timezone'] ?? 'UTC';
if (!DateTimeHelper::isValidTimezone($tz)) {
$tz = 'UTC'; // fall back to safe default
}
static now(string $format = 'Y-m-d H:i:s', string $timezone = ''): string
Get the current datetime in the app timezone (or a specific timezone override).
$format— (string) Output format. Default:'Y-m-d H:i:s'.$timezone— (string) Timezone override. Empty string = app timezone.
Returns: string — formatted current datetime.
echo DateTimeHelper::now(); // '2024-06-15 14:30:00'
echo DateTimeHelper::now('Y-m-d'); // '2024-06-15'
echo DateTimeHelper::now('H:i:s'); // '14:30:00'
echo DateTimeHelper::now('Y-m-d H:i:s', 'UTC'); // current time in UTC
static today(string $format = 'Y-m-d', string $timezone = ''): string
Get today's date in the app timezone. Shorthand for now() with a date-only default format.
$format— (string) Output format. Default:'Y-m-d'.$timezone— (string) Timezone override. Empty = app timezone.
Returns: string — today's date.
echo DateTimeHelper::today(); // '2024-06-15'
echo DateTimeHelper::today('d/m/Y'); // '15/06/2024'
echo DateTimeHelper::today('Y-m-d', 'America/New_York'); // today in New York
static tomorrow(string $format = 'Y-m-d', string $timezone = ''): string
Get tomorrow's date in the app timezone.
$format— (string) Output format. Default:'Y-m-d'.$timezone— (string) Timezone override. Empty = app timezone.
Returns: string — tomorrow's date.
echo DateTimeHelper::tomorrow(); // '2024-06-16'
echo DateTimeHelper::tomorrow('d M Y'); // '16 Jun 2024'
static yesterday(string $format = 'Y-m-d', string $timezone = ''): string
Get yesterday's date in the app timezone.
$format— (string) Output format. Default:'Y-m-d'.$timezone— (string) Timezone override. Empty = app timezone.
Returns: string — yesterday's date.
echo DateTimeHelper::yesterday(); // '2024-06-14'
echo DateTimeHelper::yesterday('d M Y'); // '14 Jun 2024'
static format(string $targetFormat, string $datetime, string $sourceFormat = 'Y-m-d H:i:s'): string
Reformat a datetime string without changing its timezone — parse it with $sourceFormat and output it with $targetFormat.
$targetFormat— (string) Desired output format.$datetime— (string) Input datetime string.$sourceFormat— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: string — reformatted datetime string.
echo DateTimeHelper::format('d/m/Y', '2024-06-15 14:30:00');
// '15/06/2024'
echo DateTimeHelper::format('M j, Y g:i A', '2024-06-15 14:30:00');
// 'Jun 15, 2024 2:30 PM'
echo DateTimeHelper::format('Y-m-d H:i:s', '15/06/2024', 'd/m/Y');
// '2024-06-15 00:00:00'
static formatForDisplay(string $datetime, string $sourceFormat = 'Y-m-d H:i:s'): string
Format a datetime for human-readable display using the pattern M j, Y g:i A. Shorthand for format('M j, Y g:i A', $datetime, $sourceFormat).
$datetime— (string) Input datetime string.$sourceFormat— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: string — human-readable date string, e.g. 'Jun 15, 2024 2:30 PM'.
echo DateTimeHelper::formatForDisplay('2024-06-15 14:30:00');
// 'Jun 15, 2024 2:30 PM'
echo DateTimeHelper::formatForDisplay('2024-01-01 00:00:00');
// 'Jan 1, 2024 12:00 AM'
static convertTimezone(string $datetime, string $fromTz, string $toTz, string $format = 'Y-m-d H:i:s', string $sourceFormat = 'Y-m-d H:i:s'): string
Convert a datetime string from one timezone to another.
$datetime— (string) Input datetime string.$fromTz— (string) Source timezone identifier.$toTz— (string) Target timezone identifier.$format— (string) Output format. Default:'Y-m-d H:i:s'.$sourceFormat— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: string — datetime converted to the target timezone.
// Warsaw (UTC+1) to Dhaka (UTC+6): +5 hours
echo DateTimeHelper::convertTimezone(
'2024-06-15 10:00:00',
'Europe/Warsaw',
'Asia/Dhaka'
);
// '2024-06-15 15:00:00'
static fromUtc(string $datetime, string $toTimezone, string $format = 'Y-m-d H:i:s'): string
Convert a UTC datetime to a target timezone for display. Shortcut for convertTimezone(..., 'UTC', $toTimezone).
$datetime— (string) UTC datetime string.$toTimezone— (string) Target timezone identifier.$format— (string) Output format. Default:'Y-m-d H:i:s'.
Returns: string — datetime in the target timezone.
$utcTime = '2024-06-15 08:00:00';
echo DateTimeHelper::fromUtc($utcTime, 'Asia/Dhaka');
// '2024-06-15 14:00:00' (UTC+6)
static toUtc(string $datetime, string $fromTimezone, string $format = 'Y-m-d H:i:s'): string
Convert a datetime from a source timezone to UTC. Shortcut for convertTimezone(..., $fromTimezone, 'UTC').
$datetime— (string) Input datetime string in the source timezone.$fromTimezone— (string) Source timezone identifier.$format— (string) Output format. Default:'Y-m-d H:i:s'.
Returns: string — datetime converted to UTC.
$localTime = '2024-06-15 14:00:00'; // Asia/Dhaka
echo DateTimeHelper::toUtc($localTime, 'Asia/Dhaka');
// '2024-06-15 08:00:00'
static forDatabase(string $datetime, string $fromTimezone = ''): string
Prepare a datetime for database storage by converting it to UTC. Uses the app timezone as the source when $fromTimezone is empty. Output is always 'Y-m-d H:i:s'.
$datetime— (string) Input datetime string.$fromTimezone— (string) Source timezone. Empty = app timezone.
Returns: string — UTC datetime string ready for database storage.
Note: Single-timezone apps do not need this — just call now() and store it directly. Use this only when users submit datetimes in their local timezone.
$userInput = '2024-06-15 14:30:00'; // in app timezone (Asia/Dhaka)
$utcValue = DateTimeHelper::forDatabase($userInput);
// '2024-06-15 08:30:00'
$app->db->table('events')->insert([
'starts_at' => $utcValue,
]);
static fromDatabase(string $datetime, string $toTimezone = '', string $format = 'Y-m-d H:i:s'): string
Convert a UTC datetime retrieved from the database to the app timezone (or any specified timezone) for display.
$datetime— (string) UTC datetime string from the database.$toTimezone— (string) Target timezone. Empty = app timezone.$format— (string) Output format. Default:'Y-m-d H:i:s'.
Returns: string — datetime in the target timezone.
$event = $app->db->table('events')->find(1);
$localTime = DateTimeHelper::fromDatabase($event['starts_at']);
echo DateTimeHelper::formatForDisplay($localTime);
// 'Jun 15, 2024 2:30 PM'
// Convert for a specific user timezone
$userTime = DateTimeHelper::fromDatabase($event['starts_at'], 'America/New_York');
static addDays(string $date, int $days, string $format = 'Y-m-d H:i:s'): string
Add a number of days to a datetime string. Pass a negative value to go backwards.
$date— (string) Input datetime string.$days— (int) Number of days to add. Negative = subtract.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — resulting datetime in the same format.
static subtractDays(string $date, int $days, string $format = 'Y-m-d H:i:s'): string
Subtract a number of days. Equivalent to addDays($date, -$days).
echo DateTimeHelper::addDays('2024-06-15', 10, 'Y-m-d'); // '2024-06-25'
echo DateTimeHelper::subtractDays('2024-06-15', 5, 'Y-m-d'); // '2024-06-10'
// Expiry date 30 days from now
$expiresAt = DateTimeHelper::addDays(DateTimeHelper::now(), 30);
static addHours(string $date, int $hours, string $format = 'Y-m-d H:i:s'): string
Add a number of hours to a datetime string.
$date— (string) Input datetime string.$hours— (int) Number of hours to add. Negative = subtract.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — resulting datetime.
static subtractHours(string $date, int $hours, string $format = 'Y-m-d H:i:s'): string
Subtract a number of hours from a datetime string.
echo DateTimeHelper::addHours('2024-06-15 10:00:00', 5); // '2024-06-15 15:00:00'
echo DateTimeHelper::subtractHours('2024-06-15 10:00:00', 3); // '2024-06-15 07:00:00'
// Session expires in 2 hours
$sessionExpiry = DateTimeHelper::addHours(DateTimeHelper::now(), 2);
static addMinutes(string $date, int $minutes, string $format = 'Y-m-d H:i:s'): string
Add a number of minutes to a datetime string.
$date— (string) Input datetime string.$minutes— (int) Number of minutes to add. Negative = subtract.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — resulting datetime.
static subtractMinutes(string $date, int $minutes, string $format = 'Y-m-d H:i:s'): string
Subtract a number of minutes from a datetime string.
echo DateTimeHelper::addMinutes('2024-06-15 14:30:00', 45); // '2024-06-15 15:15:00'
echo DateTimeHelper::subtractMinutes('2024-06-15 14:30:00', 15); // '2024-06-15 14:15:00'
// OTP valid for 10 minutes
$otpExpiry = DateTimeHelper::addMinutes(DateTimeHelper::now(), 10);
static addMonths(string $date, int $months, string $format = 'Y-m-d H:i:s'): string
Add a number of months to a datetime string.
$date— (string) Input datetime string.$months— (int) Number of months to add. Negative = subtract.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — resulting datetime.
static subtractMonths(string $date, int $months, string $format = 'Y-m-d H:i:s'): string
Subtract a number of months from a datetime string.
Note: PHP overflows short months (e.g. adding 1 month to Jan 31 produces Mar 2 or 3, not Feb 28). Wrap the result with endOfMonth() if you need the exact last day.
echo DateTimeHelper::addMonths('2024-01-15', 3, 'Y-m-d'); // '2024-04-15'
echo DateTimeHelper::subtractMonths('2024-06-15', 2, 'Y-m-d'); // '2024-04-15'
// Subscription renewal in 1 month
$renewalDate = DateTimeHelper::addMonths(DateTimeHelper::today('Y-m-d'), 1, 'Y-m-d');
static addYears(string $date, int $years, string $format = 'Y-m-d H:i:s'): string
Add a number of years to a datetime string.
$date— (string) Input datetime string.$years— (int) Number of years to add. Negative = subtract.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — resulting datetime.
static subtractYears(string $date, int $years, string $format = 'Y-m-d H:i:s'): string
Subtract a number of years from a datetime string.
echo DateTimeHelper::addYears('2024-06-15', 1, 'Y-m-d'); // '2025-06-15'
echo DateTimeHelper::subtractYears('2024-06-15', 5, 'Y-m-d'); // '2019-06-15'
// Warranty expires in 2 years
$warrantyExpiry = DateTimeHelper::addYears(DateTimeHelper::today('Y-m-d'), 2, 'Y-m-d');
static startOfDay(string $date, string $format = 'Y-m-d H:i:s'): string
Return the start of the day (00:00:00) for a given date.
$date— (string) Input datetime string.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — date at 00:00:00.
static endOfDay(string $date, string $format = 'Y-m-d H:i:s'): string
Return the end of the day (23:59:59) for a given date.
echo DateTimeHelper::startOfDay('2024-06-15 14:30:00'); // '2024-06-15 00:00:00'
echo DateTimeHelper::endOfDay('2024-06-15 14:30:00'); // '2024-06-15 23:59:59'
// Query all records for today
$start = DateTimeHelper::startOfDay(DateTimeHelper::now());
$end = DateTimeHelper::endOfDay(DateTimeHelper::now());
$rows = $app->db->table('orders')
->whereBetween('created_at', $start, $end)
->get();
static startOfWeek(string $date, string $format = 'Y-m-d H:i:s'): string
Return the start of the ISO week (Monday at 00:00:00) for a given date.
$date— (string) Input datetime string.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — Monday of the week at 00:00:00.
static endOfWeek(string $date, string $format = 'Y-m-d H:i:s'): string
Return the end of the ISO week (Sunday at 23:59:59) for a given date.
// Input: Wednesday 2024-03-20
echo DateTimeHelper::startOfWeek('2024-03-20 14:30:00'); // '2024-03-18 00:00:00' (Monday)
echo DateTimeHelper::endOfWeek('2024-03-20 14:30:00'); // '2024-03-24 23:59:59' (Sunday)
// Weekly report range
$weekStart = DateTimeHelper::startOfWeek(DateTimeHelper::now());
$weekEnd = DateTimeHelper::endOfWeek(DateTimeHelper::now());
static startOfMonth(string $date, string $format = 'Y-m-d H:i:s'): string
Return the first moment of the month (1st day at 00:00:00) for a given date.
$date— (string) Input datetime string.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — first day of the month at 00:00:00.
static endOfMonth(string $date, string $format = 'Y-m-d H:i:s'): string
Return the last moment of the month (last day at 23:59:59) for a given date.
echo DateTimeHelper::startOfMonth('2024-06-15 10:00:00'); // '2024-06-01 00:00:00'
echo DateTimeHelper::endOfMonth('2024-06-15 10:00:00'); // '2024-06-30 23:59:59'
// Monthly analytics
$start = DateTimeHelper::startOfMonth(DateTimeHelper::now());
$end = DateTimeHelper::endOfMonth(DateTimeHelper::now());
static startOfYear(string $date, string $format = 'Y-m-d H:i:s'): string
Return the first moment of the year (Jan 1 at 00:00:00) for a given date.
$date— (string) Input datetime string.$format— (string) Input and output format. Default:'Y-m-d H:i:s'.
Returns: string — January 1st at 00:00:00.
static endOfYear(string $date, string $format = 'Y-m-d H:i:s'): string
Return the last moment of the year (Dec 31 at 23:59:59) for a given date.
echo DateTimeHelper::startOfYear('2024-06-15 10:00:00'); // '2024-01-01 00:00:00'
echo DateTimeHelper::endOfYear('2024-06-15 10:00:00'); // '2024-12-31 23:59:59'
// Annual report range
$start = DateTimeHelper::startOfYear(DateTimeHelper::now());
$end = DateTimeHelper::endOfYear(DateTimeHelper::now());
static isPast(string $datetime, string $format = 'Y-m-d H:i:s'): bool
Check whether a datetime is in the past relative to now in the app timezone.
$datetime— (string) Input datetime string.$format— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: bool — true if the datetime is before now.
static isFuture(string $datetime, string $format = 'Y-m-d H:i:s'): bool
Check whether a datetime is in the future relative to now in the app timezone.
DateTimeHelper::isPast('2020-01-01 00:00:00'); // true
DateTimeHelper::isFuture('2099-12-31 23:59:59'); // true
// Check if a coupon is still valid
if (DateTimeHelper::isPast($coupon['expires_at'])) {
$errors[] = 'This coupon has expired.';
}
static isBefore(string $date1, string $date2, string $format = 'Y-m-d H:i:s'): bool
Check if $date1 is strictly before $date2.
$date1— (string) First datetime string.$date2— (string) Second datetime string.$format— (string) Input format for both dates. Default:'Y-m-d H:i:s'.
Returns: bool — true if $date1 is strictly before $date2.
static isAfter(string $date1, string $date2, string $format = 'Y-m-d H:i:s'): bool
Check if $date1 is strictly after $date2.
DateTimeHelper::isBefore('2024-01-01', '2024-06-15', 'Y-m-d'); // true
DateTimeHelper::isAfter('2024-06-15', '2024-01-01', 'Y-m-d'); // true
// Validate booking dates
if (DateTimeHelper::isBefore($checkOut, $checkIn)) {
$errors[] = 'Check-out must be after check-in.';
}
static isSameDay(string $date1, string $date2, string $format = 'Y-m-d H:i:s'): bool
Check if two datetimes fall on the same calendar day (compares the date portion only).
$date1— (string) First datetime string.$date2— (string) Second datetime string.$format— (string) Input format for both. Default:'Y-m-d H:i:s'.
Returns: bool — true if both share the same year, month, and day.
DateTimeHelper::isSameDay('2024-06-15 10:00:00', '2024-06-15 23:00:00'); // true
DateTimeHelper::isSameDay('2024-06-15 10:00:00', '2024-06-16 00:00:01'); // false
static isBetween(string $datetime, string $start, string $end, string $format = 'Y-m-d H:i:s'): bool
Check if a datetime falls within an inclusive range [$start, $end].
$datetime— (string) The datetime to test.$start— (string) Start of the range (inclusive).$end— (string) End of the range (inclusive).$format— (string) Input format for all three. Default:'Y-m-d H:i:s'.
Returns: bool — true if $datetime is within the range.
DateTimeHelper::isBetween('2024-06-15', '2024-06-01', '2024-06-30', 'Y-m-d'); // true
// Is the current time within business hours?
$now = DateTimeHelper::now('H:i:s');
if (DateTimeHelper::isBetween($now, '09:00:00', '17:00:00', 'H:i:s')) {
echo 'Office is open.';
}
static isToday(string $date, string $format = 'Y-m-d H:i:s'): bool
Check if a datetime falls on today's date in the app timezone.
static isYesterday(string $date, string $format = 'Y-m-d H:i:s'): bool
Check if a datetime falls on yesterday's date in the app timezone.
static isTomorrow(string $date, string $format = 'Y-m-d H:i:s'): bool
Check if a datetime falls on tomorrow's date in the app timezone.
All three methods accept:
$date— (string) Input datetime string.$format— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: bool
DateTimeHelper::isToday('2024-06-15 14:30:00'); // true if today is 2024-06-15
DateTimeHelper::isYesterday('2024-06-14 00:00:00'); // true if today is 2024-06-15
DateTimeHelper::isTomorrow('2024-06-16 23:59:59'); // true if today is 2024-06-15
// Show a friendly date label
$label = match(true) {
DateTimeHelper::isToday($post['created_at']) => 'Today',
DateTimeHelper::isYesterday($post['created_at']) => 'Yesterday',
default => DateTimeHelper::format('M j, Y', $post['created_at']),
};
static isWeekend(string $date, string $format = 'Y-m-d H:i:s'): bool
Check if a date falls on Saturday or Sunday.
$date— (string) Input datetime string.$format— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: bool — true if Saturday or Sunday.
static isWeekday(string $date, string $format = 'Y-m-d H:i:s'): bool
Check if a date falls on a weekday (Monday through Friday). Returns !isWeekend($date, $format).
DateTimeHelper::isWeekend('2024-03-23', 'Y-m-d'); // true (Saturday)
DateTimeHelper::isWeekend('2024-03-24', 'Y-m-d'); // true (Sunday)
DateTimeHelper::isWeekday('2024-03-25', 'Y-m-d'); // true (Monday)
// Advance to next business day
$date = DateTimeHelper::addDays(DateTimeHelper::today('Y-m-d'), 1, 'Y-m-d');
while (DateTimeHelper::isWeekend($date, 'Y-m-d')) {
$date = DateTimeHelper::addDays($date, 1, 'Y-m-d');
}
static diffInDays(string $date1, string $date2, bool $absolute = true, string $format = 'Y-m-d H:i:s'): int
Get the difference in whole days between two dates.
$date1— (string) First datetime string.$date2— (string) Second datetime string.$absolute— (bool) Return absolute value. Default:true. Whenfalse, returns a negative integer if$date2is before$date1.$format— (string) Input format for both dates. Default:'Y-m-d H:i:s'.
Returns: int — difference in whole days.
DateTimeHelper::diffInDays('2024-06-10', '2024-06-15', true, 'Y-m-d'); // 5
DateTimeHelper::diffInDays('2024-06-15', '2024-06-10', true, 'Y-m-d'); // 5 (absolute)
DateTimeHelper::diffInDays('2024-06-15', '2024-06-10', false, 'Y-m-d'); // -5 (signed)
// Days until an event
$days = DateTimeHelper::diffInDays(
DateTimeHelper::today('Y-m-d'),
$event['date'],
false,
'Y-m-d'
);
echo $days > 0 ? "in $days days" : abs($days) . " days ago";
static diffInHours(string $date1, string $date2, bool $absolute = true, string $format = 'Y-m-d H:i:s'): int
Get the difference in whole hours between two datetimes.
$date1— (string) First datetime string.$date2— (string) Second datetime string.$absolute— (bool) Return absolute value. Default:true.$format— (string) Input format for both. Default:'Y-m-d H:i:s'.
Returns: int — difference in whole hours.
DateTimeHelper::diffInHours('2024-06-15 08:00:00', '2024-06-15 20:00:00'); // 12
DateTimeHelper::diffInHours('2024-06-15 20:00:00', '2024-06-15 08:00:00', false); // -12
static diffInMinutes(string $date1, string $date2, bool $absolute = true, string $format = 'Y-m-d H:i:s'): int
Get the difference in whole minutes between two datetimes.
$date1— (string) First datetime string.$date2— (string) Second datetime string.$absolute— (bool) Return absolute value. Default:true.$format— (string) Input format for both. Default:'Y-m-d H:i:s'.
Returns: int — difference in whole minutes.
DateTimeHelper::diffInMinutes('2024-06-15 14:00:00', '2024-06-15 14:45:00'); // 45
DateTimeHelper::diffInMinutes('2024-06-15 14:00:00', '2024-06-15 16:30:00'); // 150
// How long since an action?
$minutes = DateTimeHelper::diffInMinutes($action['created_at'], DateTimeHelper::now());
echo "Last action $minutes minutes ago.";
static diffInSeconds(string $date1, string $date2, bool $absolute = true, string $format = 'Y-m-d H:i:s'): int
Get the difference in seconds between two datetimes.
$date1— (string) First datetime string.$date2— (string) Second datetime string.$absolute— (bool) Return absolute value. Default:true.$format— (string) Input format for both. Default:'Y-m-d H:i:s'.
Returns: int — difference in seconds.
DateTimeHelper::diffInSeconds('2024-06-15 14:00:00', '2024-06-15 14:01:30'); // 90
DateTimeHelper::diffInSeconds('2024-06-15 14:00:00', '2024-06-15 15:00:00'); // 3600
// Check token age
if (DateTimeHelper::diffInSeconds($token['created_at'], DateTimeHelper::now()) > 900) {
$errors[] = 'Token expired. Please request a new one.';
}
static getTimeElapsedString(string $datetime, bool $full = false, string $format = 'Y-m-d H:i:s', string $now = 'now'): string
Return a human-readable elapsed or remaining time string relative to now (or a custom reference point). Examples: '3 hours ago', 'in 2 days', '1 year, 3 months ago', 'just now'.
$datetime— (string) The datetime to describe.$full— (bool) Show all non-zero components whentrue. Default:false(largest unit only).$format— (string) Input format. Default:'Y-m-d H:i:s'.$now— (string) Reference datetime (same format), or'now'for the current time. Default:'now'.
Returns: string — human-readable time description.
// Past
echo DateTimeHelper::getTimeElapsedString('2024-01-01 10:00:00'); // '5 months ago'
echo DateTimeHelper::getTimeElapsedString('2024-01-01 10:00:00', true); // '5 months, 14 days, 4 hours ago'
// Future
echo DateTimeHelper::getTimeElapsedString('2099-01-01 00:00:00'); // 'in 74 years'
// Custom reference point
echo DateTimeHelper::getTimeElapsedString(
'2024-06-15 10:00:00',
false,
'Y-m-d H:i:s',
'2024-06-15 08:00:00'
); // 'in 2 hours'
// Post timestamps
echo DateTimeHelper::getTimeElapsedString($post['created_at']); // '3 hours ago'
static isValidDate(string $date, string $format = 'Y-m-d H:i:s'): bool
Check that a date string is a real, valid date matching the given format exactly. Uses a parse-and-reformat round-trip so overflowing dates like Feb 30 or month 13 correctly return false.
$date— (string) The date string to validate.$format— (string) The expected format. Default:'Y-m-d H:i:s'.
Returns: bool — true if the string is a valid date in the given format.
DateTimeHelper::isValidDate('2024-03-15 10:30:00'); // true
DateTimeHelper::isValidDate('2024-02-30 00:00:00'); // false (Feb 30 does not exist)
DateTimeHelper::isValidDate('2024-13-01', 'Y-m-d'); // false (month 13)
DateTimeHelper::isValidDate('not-a-date'); // false
DateTimeHelper::isValidDate('2024-03-15', 'Y-m-d'); // true
// Validate user input before processing
$date = $_POST['event_date'] ?? '';
if (!DateTimeHelper::isValidDate($date, 'Y-m-d')) {
$errors[] = 'Invalid date. Please use YYYY-MM-DD format.';
}
static age(string $birthdate, string $format = 'Y-m-d'): int
Calculate a person's age in whole completed years from a birthdate to today in the app timezone.
$birthdate— (string) Birthdate string.$format— (string) Input format. Default:'Y-m-d'.
Returns: int — age in whole completed years.
DateTimeHelper::age('1990-05-15'); // e.g. 34
// Minimum age check
$birthdate = $_POST['birthdate'] ?? '';
if (!DateTimeHelper::isValidDate($birthdate, 'Y-m-d')) {
$errors[] = 'Invalid date of birth.';
} elseif (DateTimeHelper::age($birthdate) < 18) {
$errors[] = 'You must be at least 18 years old.';
}
static getWeekday(string $date, string $format = 'Y-m-d H:i:s'): string
Return the full English weekday name for a date.
$date— (string) Input datetime string.$format— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: string — full weekday name, e.g. 'Monday', 'Friday'.
echo DateTimeHelper::getWeekday('2024-06-15', 'Y-m-d'); // 'Saturday'
echo DateTimeHelper::getWeekday('2024-03-18', 'Y-m-d'); // 'Monday'
echo "Event falls on a " . DateTimeHelper::getWeekday($event['date'], 'Y-m-d');
static toTimestamp(string $datetime, string $timezone = '', string $format = 'Y-m-d H:i:s'): int
Convert a datetime string to a Unix timestamp.
$datetime— (string) Input datetime string.$timezone— (string) Timezone of the input string. Empty = app timezone.$format— (string) Input format. Default:'Y-m-d H:i:s'.
Returns: int — Unix timestamp.
$ts = DateTimeHelper::toTimestamp('2024-06-15 14:30:00');
echo $ts; // e.g. 1718457000
// Pass the expiry time to a front-end countdown timer
$expiry = DateTimeHelper::toTimestamp($session['expires_at']);
static fromTimestamp(int $timestamp, string $timezone = '', string $format = 'Y-m-d H:i:s'): string
Convert a Unix timestamp to a datetime string in the app timezone (or a specified timezone).
$timestamp— (int) Unix timestamp.$timezone— (string) Output timezone. Empty = app timezone.$format— (string) Output format. Default:'Y-m-d H:i:s'.
Returns: string — formatted datetime string.
echo DateTimeHelper::fromTimestamp(1718457000);
// '2024-06-15 14:30:00' (in app timezone)
echo DateTimeHelper::fromTimestamp(1718457000, 'UTC');
// '2024-06-15 08:30:00'
echo DateTimeHelper::fromTimestamp(1718457000, '', 'M j, Y');
// 'Jun 15, 2024'
static getDateDifference(string $date1, string $date2, bool $absolute = false, string $format = 'Y-m-d H:i:s'): DateInterval
Get a DateInterval object representing the difference between two dates. For simple numeric differences prefer diffInDays(), diffInHours(), etc. Use this when you need the full breakdown (years, months, days, hours, minutes, seconds together).
$date1— (string) First datetime string.$date2— (string) Second datetime string.$absolute— (bool) Return absolute interval. Default:false.$format— (string) Input format for both. Default:'Y-m-d H:i:s'.
Returns: DateInterval
$diff = DateTimeHelper::getDateDifference(
'2022-01-15',
'2024-06-20',
false,
'Y-m-d'
);
echo $diff->y . " years, " . $diff->m . " months, " . $diff->d . " days";
// '2 years, 5 months, 5 days'
Store and display datetimes across timezones
// Save user event to database in UTC
$localInput = $_POST['starts_at']; // '2024-06-15 18:00:00' in Asia/Dhaka
$utcValue = DateTimeHelper::forDatabase($localInput);
$app->db->table('events')->insert(['starts_at' => $utcValue]);
// Display in local time
$row = $app->db->table('events')->find(1);
$local = DateTimeHelper::fromDatabase($row['starts_at']);
echo DateTimeHelper::formatForDisplay($local); // 'Jun 15, 2024 6:00 PM'
Build an activity feed with relative timestamps
$posts = $app->db->table('posts')->orderBy('created_at', 'DESC')->get();
foreach ($posts as $post) {
$label = match(true) {
DateTimeHelper::isToday($post['created_at']) => 'Today',
DateTimeHelper::isYesterday($post['created_at']) => 'Yesterday',
default => DateTimeHelper::format('M j', $post['created_at']),
};
$ago = DateTimeHelper::getTimeElapsedString($post['created_at']);
echo "$label — $ago";
}
Weekly report query
$weekStart = DateTimeHelper::startOfWeek(DateTimeHelper::now());
$weekEnd = DateTimeHelper::endOfWeek(DateTimeHelper::now());
$sales = $app->db->table('orders')
->whereBetween('created_at', $weekStart, $weekEnd)
->sum('total');
echo "This week's sales: $" . number_format($sales, 2);
Age verification
$birthdate = $_POST['birthdate'] ?? '';
if (!DateTimeHelper::isValidDate($birthdate, 'Y-m-d')) {
$app->abort(422, 'Invalid date of birth.');
}
if (DateTimeHelper::age($birthdate) < 18) {
$app->abort(403, 'You must be at least 18 years old.');
}
Skip weekends when scheduling
$date = DateTimeHelper::addDays(DateTimeHelper::today('Y-m-d'), 1, 'Y-m-d');
while (DateTimeHelper::isWeekend($date, 'Y-m-d')) {
$date = DateTimeHelper::addDays($date, 1, 'Y-m-d');
}
echo "Next business day: $date";