PHP Class Tools\Utility\Time

Inheritance: extends Cake\I18n\Time
Datei anzeigen Open project: dereuromark/cakephp-tools Class Usage Examples

Public Methods

Method Description
__construct ( $time = null, $tz = null ) {@inheritDoc}
age ( integer | string $start, integer | string | null $end = null ) : integer Calculates the age using start and optional end date.
ageBounds ( integer $firstAge, integer | null $secondAge = null, boolean $returnAsString = false, string | null $relativeTime = null ) : array Get the age bounds (min, max) as timestamp that would result in the given age(s) note: expects valid age (> 0 and < 120)
ageByHoroscope ( integer $year, integer $sign ) : integer | array Returns age by horoscope info.
ageByYear ( integer $year, integer | null $month = null ) : integer | string Returns the age only with the year available can be e.g. 22/23
ageRange ( integer $year, integer | null $month = null, integer | null $day = null, integer $steps = 1 ) : mixed Rounded age depended on steps (e.g. age 16 with steps = 10 => "11-20") FIXME TODO: move to helper?
buildDefaultTime ( integer $duration ) : string Return strings like 2:33:99 from seconds etc
buildTime ( integer | DateInterval $duration, string $format = 'H:MM:SS' ) : string Returns nicely formatted duration difference as string like 2:30 or 2:30:06.
cWeek ( mixed | null $dateString = null, integer $relative ) : string Calendar Week (current week of the year).
cWeekBeginning ( integer $year, integer $cWeek ) : integer Calculate the beginning of a calender week if no calendar week is given get the beginning of the first week of the year
cWeekEnding ( integer $year, integer $cWeek ) : integer Calculate the ending of a calenderweek if no cweek is given get the ending of the last week of the year
cWeekMod ( integer $num ) : integer Get number of days since the start of the week.
cWeeks ( integer | null $year = null ) : integer Calculate the amount of calender weeks in a year
convertDate ( string $oldDateString, string $newDateFormatString, integer | null $timezone = null ) : string Convenience method to convert a given date
dayAsSql ( integer | string | DateTime $dateString, string $fieldName, string | DateTimeZone | null $timezone = null ) : string Returns a partial SQL string to search for all records between two times occurring on the same day.
dayName ( integer $day, boolean $abbr = false, integer $offset ) : string Return the translation to a specific week day
dayNames ( array $dayKeys = [], array $options = [] ) : array Weekdays
daysAsSql ( integer | string | DateTime $begin, integer | string | DateTime $end, string $fieldName, string | DateTimeZone | null $timezone = null ) : string Returns a partial SQL string to search for all records between two dates.
daysInMonth ( integer $year, integer $month ) : string Return the days of a given month.
decimalToStandardTime ( integer $value, string | null $pad = null, string $decPoint = '.' ) : string Hours, minutes e.g. 9.5 => 9.3 with pad=2: 9.30
difference ( mixed $startTime, mixed | null $endTime = null, array $options = [] ) : integer Calculate the difference between two dates
duration ( integer | DateInterval $duration, string $format = '%h:%I:%S' ) : string Returns nicely formatted duration difference as string like 2:30 (H:MM) or 2:30:06 (H:MM:SS) etc.
fuzzy ( integer $timestamp ) : string Returns the difference between a time and now in a "fuzzy" way.
fuzzyFromOffset ( integer $offset, boolean | null $past = null ) : string
getGmtOffset ( string | DateTimeZone | null $timezone = null ) : integer Calculate the current GMT offset from a timezone string (respecting DST)
hasDaylightSavingTime ( string | DateTimeZone | null $timezone = null ) : boolean Detect if a timezone has a DST
incrementDate ( mixed $startDate, integer $years, integer $months, integer $days, string | DateTimeZone | integer | null $timezone = null ) : object Handles month/year increment calculations in a safe way, avoiding the pitfall of "fuzzy" month units.
isDayAfterTomorrow ( string $dateString, integer | null $timezone = null ) : boolean Returns true if given datetime string is the day after tomorrow.
isInRange ( string $dateString, integer $seconds ) : boolean For birthdays etc
isInTheFuture ( string $dateString, integer | null $timezone = null ) : boolean Returns true if given datetime string is not now AND is in the future.
isNotTodayAndInTheFuture ( string $dateString, integer | null $timezone = null ) : boolean Returns true if given datetime string is not today AND is in the future.
lengthOfTime ( integer $seconds, string | null $format = null, array $options = [] ) : string Time length to human readable format.
localDate ( string | null $dateString = null, string | null $format = null, array $options = [] ) : string Outputs Date(time) Sting nicely formatted (+ localized!)
monthName ( integer $month, boolean $abbr = false, array $options = [] ) : string Return the translation to a specific week day
monthNames ( array $monthKeys = [], array $options = [] ) : array Months
niceDate ( string | null $dateString = null, string | null $format = null, array $options = [] ) : string Outputs Date(time) Sting nicely formatted
niceTime ( string $time ) : string Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss
pad ( string $value, integer $length = 2, string $string = '0' ) : string TimeLib::pad()
parseLocalDate ( string $date, array $allowed = ['.', '-'] ) : integer Parse 2022-11-12 or 12.11.2022 or even 12.11.22
parseLocalTime ( string $duration, array $allowed = [':', '.', ','] ) : integer Parse 2,5 - 2.5 2:30 2:31:58 or even 2011-11-12 10:10:10 now supports negative values like -2,5 -2,5 -2:30 -:30 or -4
parseLocalizedDate ( string $date, string | null $format = null, string $type = 'start' ) : string Try to parse date from various input formats - DD.MM.YYYY, DD/MM/YYYY, YYYY-MM-DD, YYYY, YYYY-MM, .
period ( string $searchString, array $options = [] ) : array Parse a period (from .
periodAsSql ( string $searchString, string $fieldName, array $options = [] ) : string Return SQL snippet for a period (beginning till end).
relLengthOfTime ( mixed $date, string | null $format = null, array $options = [] ) : string Time relative to NOW in human readable format - absolute (negative as well as positive) TODO: make "now" adjustable
standardToDecimalTime ( integer $value ) : float Hours, minutes e.g. 9.3 => 9.5
timezoneByCoordinates ( float $lat, float $lng ) : DateTimeZone Gets the timezone that is closest to the given coordinates
tzOffset ( integer $gmtoffset, boolean $isDst ) : integer EXPERIMENTAL!!!
wasDayBeforeYesterday ( string $dateString, integer | null $timezone = null ) : boolean Returns true if given datetime string was day before yesterday.

Protected Methods

Method Description
_strftime ( string $format, integer $date ) : string Multibyte wrapper for strftime.

Method Details

__construct() public method

{@inheritDoc}
public __construct ( $time = null, $tz = null )

_strftime() protected static method

Handles utf8_encoding the result of strftime when necessary.
protected static _strftime ( string $format, integer $date ) : string
$format string Format string.
$date integer Timestamp to format.
return string formatted string with correct encoding.

age() public static method

Both dates default to current date. Note that start needs to be before end for a valid result.
public static age ( integer | string $start, integer | string | null $end = null ) : integer
$start integer | string Start date (if empty, use today)
$end integer | string | null End date (if empty, use today)
return integer Age (0 if both timestamps are equal or empty, -1 on invalid dates)

ageBounds() public static method

Get the age bounds (min, max) as timestamp that would result in the given age(s) note: expects valid age (> 0 and < 120)
public static ageBounds ( integer $firstAge, integer | null $secondAge = null, boolean $returnAsString = false, string | null $relativeTime = null ) : array
$firstAge integer
$secondAge integer | null (defaults to first one if not specified)
$returnAsString boolean
$relativeTime string | null
return array Array('min'=>$min, 'max'=>$max);

ageByHoroscope() public static method

Returns age by horoscope info.
public static ageByHoroscope ( integer $year, integer $sign ) : integer | array
$year integer Year
$sign integer Sign
return integer | array Age

ageByYear() public static method

Returns the age only with the year available can be e.g. 22/23
public static ageByYear ( integer $year, integer | null $month = null ) : integer | string
$year integer
$month integer | null (optional)
return integer | string Age

ageRange() public static method

Rounded age depended on steps (e.g. age 16 with steps = 10 => "11-20") FIXME TODO: move to helper?
public static ageRange ( integer $year, integer | null $month = null, integer | null $day = null, integer $steps = 1 ) : mixed
$year integer
$month integer | null
$day integer | null
$steps integer
return mixed

buildDefaultTime() public static method

Return strings like 2:33:99 from seconds etc
public static buildDefaultTime ( integer $duration ) : string
$duration integer Duration in seconds
return string Time

buildTime() public static method

Note that the more than hours is currently not supported. Note that duration with DateInterval supports only values < month with accuracy, as it approximates month as "30".
Deprecation: Use duration() instead?
public static buildTime ( integer | DateInterval $duration, string $format = 'H:MM:SS' ) : string
$duration integer | DateInterval Duration in seconds or as DateInterval object
$format string Defaults to hours and minutes
return string Time

cWeek() public static method

TODO: use timestamp - or make the function able to use timestamps at least (besides dateString) date('W', $time) returns ISO6801 week number. Exception: Dates of the calender week of the previous year return 0. In this case the cweek of the last week of the previous year should be used.
public static cWeek ( mixed | null $dateString = null, integer $relative ) : string
$dateString mixed | null In DB format - if none is passed, current day is used
$relative integer - weeks relative to the date (+1 next, -1 previous etc)
return string

cWeekBeginning() public static method

Calculate the beginning of a calender week if no calendar week is given get the beginning of the first week of the year
public static cWeekBeginning ( integer $year, integer $cWeek ) : integer
$year integer (format xxxx)
$cWeek integer (optional, defaults to first, range 1...52/53)
return integer Timestamp

cWeekEnding() public static method

Calculate the ending of a calenderweek if no cweek is given get the ending of the last week of the year
public static cWeekEnding ( integer $year, integer $cWeek ) : integer
$year integer (format xxxx)
$cWeek integer (optional, defaults to last, range 1...52/53)
return integer Timestamp

cWeekMod() public static method

0=sunday to 7=saturday (default)
public static cWeekMod ( integer $num ) : integer
$num integer Number of day.
return integer Days since the start of the week.

cWeeks() public static method

Calculate the amount of calender weeks in a year
public static cWeeks ( integer | null $year = null ) : integer
$year integer | null (format xxxx, defaults to current year)
return integer Amount of weeks - 52 or 53

convertDate() public static method

Convenience method to convert a given date
public static convertDate ( string $oldDateString, string $newDateFormatString, integer | null $timezone = null ) : string
$oldDateString string
$newDateFormatString string
$timezone integer | null User's timezone
return string Formatted date

dayAsSql() public static method

Returns a partial SQL string to search for all records between two times occurring on the same day.
public static dayAsSql ( integer | string | DateTime $dateString, string $fieldName, string | DateTimeZone | null $timezone = null ) : string
$dateString integer | string | DateTime UNIX timestamp, strtotime() valid string or DateTime object
$fieldName string Name of database field to compare with
$timezone string | DateTimeZone | null Timezone string or DateTimeZone object
return string Partial SQL string.

dayName() public static method

Return the translation to a specific week day
public static dayName ( integer $day, boolean $abbr = false, integer $offset ) : string
$day integer 0=sunday to 7=saturday (default numbers)
$abbr boolean (if abbreviation should be returned)
$offset integer int 0-6 (defaults to 0) [1 => 1=monday to 7=sunday]
return string translatedText

dayNames() public static method

Weekdays
public static dayNames ( array $dayKeys = [], array $options = [] ) : array
$dayKeys array
$options array
return array

daysAsSql() public static method

Returns a partial SQL string to search for all records between two dates.
public static daysAsSql ( integer | string | DateTime $begin, integer | string | DateTime $end, string $fieldName, string | DateTimeZone | null $timezone = null ) : string
$begin integer | string | DateTime UNIX timestamp, strtotime() valid string or DateTime object
$end integer | string | DateTime UNIX timestamp, strtotime() valid string or DateTime object
$fieldName string Name of database field to compare with
$timezone string | DateTimeZone | null Timezone string or DateTimeZone object
return string Partial SQL string.

daysInMonth() public static method

Return the days of a given month.
public static daysInMonth ( integer $year, integer $month ) : string
$year integer
$month integer
return string Days

decimalToStandardTime() public static method

Hours, minutes e.g. 9.5 => 9.3 with pad=2: 9.30
public static decimalToStandardTime ( integer $value, string | null $pad = null, string $decPoint = '.' ) : string
$value integer
$pad string | null
$decPoint string
return string

difference() public static method

TODO: deprecate in favor of DateTime::diff() etc which will be more precise should only be used for < month (due to the different month lenghts it gets fuzzy)
public static difference ( mixed $startTime, mixed | null $endTime = null, array $options = [] ) : integer
$startTime mixed (db format or timestamp)
$endTime mixed | null (db format or timestamp)
$options array
return integer The distance in seconds

duration() public static method

Note that the more than days is currently not supported accurately. E.g. for days and hours set format to: $d:$H
public static duration ( integer | DateInterval $duration, string $format = '%h:%I:%S' ) : string
$duration integer | DateInterval Duration in seconds or as DateInterval object
$format string Defaults to hours, minutes and seconds
return string Time

fuzzy() public static method

Note that unlike [span], the "local" timestamp will always be the current time. Displaying a fuzzy time instead of a date is usually faster to read and understand. $span = fuzzy(time() - 10); // "moments ago" $span = fuzzy(time() + 20); // "in moments"
public static fuzzy ( integer $timestamp ) : string
$timestamp integer "remote" timestamp
return string

fuzzyFromOffset() public static method

public static fuzzyFromOffset ( integer $offset, boolean | null $past = null ) : string
$offset integer in seconds
$past boolean | null (defaults to null: return plain text) - new: if not boolean but a string use this as translating text
return string text (i18n!)

getGmtOffset() public method

Calculate the current GMT offset from a timezone string (respecting DST)
public getGmtOffset ( string | DateTimeZone | null $timezone = null ) : integer
$timezone string | DateTimeZone | null User's timezone string or DateTimeZone object
return integer Offset in hours

hasDaylightSavingTime() public method

Detect if a timezone has a DST
public hasDaylightSavingTime ( string | DateTimeZone | null $timezone = null ) : boolean
$timezone string | DateTimeZone | null User's timezone string or DateTimeZone object
return boolean

incrementDate() public method

Handles month/year increment calculations in a safe way, avoiding the pitfall of "fuzzy" month units.
public incrementDate ( mixed $startDate, integer $years, integer $months, integer $days, string | DateTimeZone | integer | null $timezone = null ) : object
$startDate mixed Either a date string or a DateTime object
$years integer Years to increment/decrement
$months integer Months to increment/decrement
$days integer Days
$timezone string | DateTimeZone | integer | null Timezone string or DateTimeZone object
return object DateTime with incremented/decremented month/year values.

isDayAfterTomorrow() public static method

Returns true if given datetime string is the day after tomorrow.
public static isDayAfterTomorrow ( string $dateString, integer | null $timezone = null ) : boolean
$dateString string Datetime string or Unix timestamp
$timezone integer | null User's timezone
return boolean True if datetime string is day after tomorrow

isInRange() public static method

For birthdays etc
public static isInRange ( string $dateString, integer $seconds ) : boolean
$dateString string
$seconds integer
return boolean Success

isInTheFuture() public static method

Returns true if given datetime string is not now AND is in the future.
public static isInTheFuture ( string $dateString, integer | null $timezone = null ) : boolean
$dateString string Datetime string or Unix timestamp
$timezone integer | null User's timezone
return boolean True if datetime is not today AND is in the future

isNotTodayAndInTheFuture() public static method

Returns true if given datetime string is not today AND is in the future.
public static isNotTodayAndInTheFuture ( string $dateString, integer | null $timezone = null ) : boolean
$dateString string Datetime string or Unix timestamp
$timezone integer | null User's timezone
return boolean True if datetime is not today AND is in the future

lengthOfTime() public static method

Time length to human readable format.
See also: timeAgoInWords()
public static lengthOfTime ( integer $seconds, string | null $format = null, array $options = [] ) : string
$seconds integer
$format string | null
$options array - boolean v: verbose - boolean zero: if false: 0 days 5 hours => 5 hours etc. - int: accuracy (how many sub-formats displayed?) //TODO
return string

localDate() public static method

Options: - timezone: User's timezone - default: Default string (defaults to "-----") - oclock: Set to true to append oclock string
public static localDate ( string | null $dateString = null, string | null $format = null, array $options = [] ) : string
$dateString string | null
$format string | null Format (YYYY-MM-DD, DD.MM.YYYY)
$options array
return string

monthName() public static method

Return the translation to a specific week day
public static monthName ( integer $month, boolean $abbr = false, array $options = [] ) : string
$month integer 1..12
$abbr boolean (if abbreviation should be returned)
$options array - appendDot (only for 3 letter abbr; defaults to false)
return string translatedText

monthNames() public static method

Months
public static monthNames ( array $monthKeys = [], array $options = [] ) : array
$monthKeys array
$options array
return array

niceDate() public static method

Options: - timezone: User's timezone - default: Default string (defaults to "-----") - oclock: Set to true to append oclock string
public static niceDate ( string | null $dateString = null, string | null $format = null, array $options = [] ) : string
$dateString string | null
$format string | null Format (YYYY-MM-DD, DD.MM.YYYY)
$options array Options
return string

niceTime() public static method

Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss
public static niceTime ( string $time ) : string
$time string
return string Time in format hh:mm

pad() public static method

TimeLib::pad()
public static pad ( string $value, integer $length = 2, string $string = '0' ) : string
$value string
$length integer
$string string
return string

parseLocalDate() public static method

Parse 2022-11-12 or 12.11.2022 or even 12.11.22
public static parseLocalDate ( string $date, array $allowed = ['.', '-'] ) : integer
$date string
$allowed array
return integer Seconds

parseLocalTime() public static method

Parse 2,5 - 2.5 2:30 2:31:58 or even 2011-11-12 10:10:10 now supports negative values like -2,5 -2,5 -2:30 -:30 or -4
public static parseLocalTime ( string $duration, array $allowed = [':', '.', ','] ) : integer
$duration string
$allowed array
return integer Seconds

parseLocalizedDate() public static method

.. - i18n: Today, Yesterday, Tomorrow
public static parseLocalizedDate ( string $date, string | null $format = null, string $type = 'start' ) : string
$date string to parse
$format string | null Format to parse (null = auto)
$type string - start: first second of this interval - end: last second of this interval
return string timestamp

period() public static method

.. to)
public static period ( string $searchString, array $options = [] ) : array
$searchString string Search string to parse
$options array - separator (defaults to space [ ]) - format (defaults to Y-m-d H:i:s)
return array period [0=>min, 1=>max]

periodAsSql() public static method

Return SQL snippet for a period (beginning till end).
public static periodAsSql ( string $searchString, string $fieldName, array $options = [] ) : string
$searchString string to parse
$fieldName string (Model.field)
$options array (see TimeLib::period)
return string query SQL Query

relLengthOfTime() public static method

Time relative to NOW in human readable format - absolute (negative as well as positive) TODO: make "now" adjustable
public static relLengthOfTime ( mixed $date, string | null $format = null, array $options = [] ) : string
$date mixed
$format string | null Format
$options array Options - default, separator - boolean zero: if false: 0 days 5 hours => 5 hours etc. - verbose/past/future: string with %s or boolean true/false
return string

standardToDecimalTime() public static method

Hours, minutes e.g. 9.3 => 9.5
public static standardToDecimalTime ( integer $value ) : float
$value integer
return float

timezoneByCoordinates() public static method

Gets the timezone that is closest to the given coordinates
Deprecation: Would need Geo plugin to work
public static timezoneByCoordinates ( float $lat, float $lng ) : DateTimeZone
$lat float
$lng float
return DateTimeZone Timezone object

tzOffset() public static method

EXPERIMENTAL!!!
public static tzOffset ( integer $gmtoffset, boolean $isDst ) : integer
$gmtoffset integer Offset in seconds
$isDst boolean If DST
return integer offset Calculated offset

wasDayBeforeYesterday() public static method

Returns true if given datetime string was day before yesterday.
public static wasDayBeforeYesterday ( string $dateString, integer | null $timezone = null ) : boolean
$dateString string Datetime string or Unix timestamp
$timezone integer | null User's timezone
return boolean True if datetime string was day before yesterday