DateTimeHelper

Introduction

The DateTimeHelper class in JiFramework provides a comprehensive set of static methods for working with dates and times. It simplifies common date and time operations, such as converting between formats, calculating differences, and generating human-readable time strings. By leveraging this class, developers can handle date and time functionality consistently across their applications.

Configurable Timezone:

The default timezone used by the DateTimeHelper can be set in the Config class using the TIMEZONE constant. If not set, it falls back to the system's default timezone. This allows you to ensure that all date and time operations within your application use the correct timezone.

Usage: 

// Option 1: Initialize the DateTimeHelper through the App
use JIFramework\Core\App\App;

$app = new App();
$dateTimeHelper = $app->dateTimeHelper;

// Option 2: Use DateTimeHelper statically without instantiation
use JIFramework\Core\Utilities\DateTimeHelper;

// Directly call static methods
$currentDatetime = DateTimeHelper::getCurrentDatetime();

Explanation:

  • Option 1: Initializes the App class and retrieves the DateTimeHelper instance through it, using the framework's main entry point.
  • Option 2: Uses the DateTimeHelper class statically without the need to instantiate it.

getDefaultTimezone()

Method: getDefaultTimezone(): string

Description: Retrieves the application's default timezone as defined in the configuration or the system's default timezone if not set.

Parameters: None

Returns: A string representing the default timezone.

Usage:

$timezone = DateTimeHelper::getDefaultTimezone();
echo "Default Timezone: " . $timezone;

/*
Sample Output:

Default Timezone: America/New_York
*/

Explanation:

  • Checks if TIMEZONE is defined in the Config class.
  • Returns the configured timezone or falls back to date_default_timezone_get().

datetimeToTimestamp()

Method: datetimeToTimestamp(string $datetime, string $format = 'Y-m-d H:i:s'): int

Description: Converts a datetime string to a Unix timestamp.

Parameters:

  • $datetime (string): The datetime string to convert.
  • $format (string, optional): The format of the input datetime string. Default is 'Y-m-d H:i:s'.

Returns: An int representing the Unix timestamp.

Throws:

  • Exception: If the datetime cannot be parsed.

Usage:

$timestamp = DateTimeHelper::datetimeToTimestamp('2023-10-15 14:30:00');

/*
Sample $timestamp:

1697389800
*/

echo "Timestamp: " . $timestamp;

Explanation:

  • Uses DateTime::createFromFormat() to parse the datetime string.
  • Returns the Unix timestamp using getTimestamp().

timestampToDatetime()

Method: timestampToDatetime(int $timestamp, string $format = 'Y-m-d H:i:s'): string

Description: Converts a Unix timestamp to a formatted datetime string.

Parameters:

  • $timestamp (int): The Unix timestamp to convert.
  • $format (string, optional): The desired output format. Default is 'Y-m-d H:i:s'.

Returns: A string representing the formatted datetime.

Usage:

$datetime = DateTimeHelper::timestampToDatetime(1697389800);

/*
Sample $datetime:

"2023-10-15 14:30:00"
*/

echo "Datetime: " . $datetime;

Explanation:

  • Uses PHP's date() function to format the timestamp.

formatDate()

Method: formatDate(string $targetFormat, string $dateString, string $sourceFormat = ''): string|false

Description: 

Converts a date string from one format to another, optionally specifying the source format.

Parameters:

  • $targetFormat (string): The target date format, as specified by PHP's date() function.
  • $dateString (string): The input date string to be converted.
  • $sourceFormat (string, optional): The source date format. If provided, used to parse $dateString.

Returns: 

The formatted date string, or false if the input date is invalid or conversion fails.

Usage:

$formattedDate = DateTimeHelper::formatDate('d/m/Y', '2023-10-15', 'Y-m-d');

/*
Sample $formattedDate:

"15/10/2023"
*/

echo "Formatted Date: " . $formattedDate;

Explanation:

  • Parses the input date string using the source format if provided.
  • Converts the date to the target format.
  • Returns false if parsing fails.

getTimeElapsedString()

Method: getTimeElapsedString(string $datetime, bool $full = false, string $format = 'Y-m-d H:i:s', $now = 'now'): string

Description: Generates a human-readable string representing the time elapsed since a given datetime.

Parameters:

  • $datetime (string): The datetime string to compare.
  • $full (bool, optional): Whether to return the full time difference. Default is false.
  • $format (string, optional): The format of the datetime string. Default is 'Y-m-d H:i:s'.
  • $now (string|DateTime, optional): The current datetime or 'now'. Default is 'now'.

Returns: A string representing the elapsed time (e.g., "2 days ago").

Throws:

  • Exception: If the datetime cannot be parsed.

Usage:

$elapsedTime = DateTimeHelper::getTimeElapsedString('2023-10-13 12:00:00');

/*
Sample $elapsedTime (assuming current date is 2023-10-15):

"2 days ago"
*/

echo $elapsedTime;

Explanation:

  • Calculates the difference between the provided datetime and the current time.
  • Formats the difference into a human-readable string.
  • If $full is true, includes all time components (e.g., "2 days, 3 hours ago").

getDateDifference()

Method: getDateDifference(string $dateTime1, string $dateTime2, bool $absolute = false, string $format = 'Y-m-d H:i:s'): DateInterval

Description: Calculates the difference between two dates.

Parameters:

  • $dateTime1 (string): The first date and time.
  • $dateTime2 (string): The second date and time.
  • $absolute (bool, optional): Whether to return the absolute difference. Default is false.
  • $format (string, optional): The format of the input dates. Default is 'Y-m-d H:i:s'.

Returns: A DateInterval object representing the difference.

Throws:

  • Exception: If the dates cannot be parsed.

Usage:

$interval = DateTimeHelper::getDateDifference('2023-10-10 08:00:00', '2023-10-15 14:30:00');

/*
Sample $interval:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 5
    [h] => 6
    [i] => 30
    [s] => 0
    // Other properties...
)
*/

echo "Difference: " . $interval->format('%d days, %h hours, %i minutes');

/*
Sample Output:

Difference: 5 days, 6 hours, 30 minutes
*/

Explanation:

  • Parses both dates and calculates the difference.
  • Returns a DateInterval object, which can be formatted as needed.

isValidDate()

Method: isValidDate(string $date, string $format = 'Y-m-d H:i:s'): bool

Description: Validates whether a date string conforms to a specified format.

Parameters:

  • $date (string): The date string to validate.
  • $format (string, optional): The expected date format. Default is 'Y-m-d H:i:s'.

Returns: 

true if the date is valid; false otherwise.

Usage:

$isValid = DateTimeHelper::isValidDate('2023-10-15 14:30:00');

/*
Sample $isValid:

true
*/

echo $isValid ? 'Valid Date' : 'Invalid Date';

Explanation:

  • Uses DateTime::createFromFormat() and compares the formatted date to the input.
  • Helps ensure date strings are correctly formatted before processing.

getWeekday()

Method: getWeekday(string $date, string $format = 'Y-m-d H:i:s'): string

Description: Retrieves the weekday name for a given date.

Parameters:

  • $date (string): The date string.
  • $format (string, optional): The format of the date string. Default is 'Y-m-d H:i:s'.

Returns: 

A string representing the weekday name (e.g., "Monday").

Throws:

  • Exception: If the date cannot be parsed.

Usage:

$weekday = DateTimeHelper::getWeekday('2023-10-15 14:30:00');

/*
Sample $weekday:

"Sunday"
*/

echo "Weekday: " . $weekday;

Explanation:

  • Parses the date and formats it to return the full textual representation of the weekday.

addDays()

Method: addDays(string $date, int $days, string $format = 'Y-m-d H:i:s'): string

Description: Adds a specified number of days to a date.

Parameters:

  • $date (string): The original date string.
  • $days (int): The number of days to add.
  • $format (string, optional): The format of the date string. Default is 'Y-m-d H:i:s'.

Returns: 

A string representing the new date after adding days.

Throws:

  • Exception: If the date cannot be parsed.

Usage:

$newDate = DateTimeHelper::addDays('2023-10-15 14:30:00', 5);

/*
Sample $newDate:

"2023-10-20 14:30:00"
*/

echo "New Date: " . $newDate;

Explanation:

  • Parses the original date.
  • Modifies the date by adding the specified number of days.
  • Returns the new date in the specified format.

subtractDays()

Method: subtractDays(string $date, int $days, string $format = 'Y-m-d H:i:s'): string

Description: Subtracts a specified number of days from a date.

Parameters:

  • $date (string): The original date string.
  • $days (int): The number of days to subtract.
  • $format (string, optional): The format of the date string. Default is 'Y-m-d H:i:s'.

Returns: A string representing the new date after subtracting days.

Throws:

  • Exception: If the date cannot be parsed.

Usage:

$newDate = DateTimeHelper::subtractDays('2023-10-15 14:30:00', 3);

/*
Sample $newDate:

"2023-10-12 14:30:00"
*/

echo "New Date: " . $newDate;

Explanation:

  • Calls addDays() internally with a negative number of days.
  • Returns the adjusted date.

getCurrentDatetime()

Method: getCurrentDatetime(string $format = 'Y-m-d H:i:s', string $timezone = ''): string

Description: Retrieves the current datetime in a specified format and timezone.

Parameters:

  • $format (string, optional): The desired output format. Default is 'Y-m-d H:i:s'.
  • $timezone (string, optional): The timezone identifier. If empty, uses the default timezone from the configuration.

Returns: A string representing the current datetime.

Throws:

  • Exception: If the timezone is invalid.

Usage:

$currentDatetime = DateTimeHelper::getCurrentDatetime();

/*
Sample $currentDatetime:

"2023-10-15 14:30:00"
*/

echo "Current Datetime: " . $currentDatetime;

Explanation:

  • Creates a new DateTime object for 'now' in the specified or default timezone.
  • Formats the datetime according to the provided format.

getSupportedTimezones()

Method: getSupportedTimezones(): array

Description: Retrieves a list of all supported timezone identifiers.

Parameters: None

Returns: An array of timezone identifiers.

Usage:

$timezones = DateTimeHelper::getSupportedTimezones();

/*
Sample $timezones:

Array
(
    [0] => Africa/Abidjan
    [1] => Africa/Accra
    [2] => Africa/Addis_Ababa
    // ...
)
*/

print_r($timezones);

Explanation:

  • Uses DateTimeZone::listIdentifiers() to get all timezone identifiers.
  • Useful for populating timezone selection lists in applications.