PHP Class Tools\Utility\Time

Inheritance: extends Cake\I18n\Time
Afficher le fichier Open project: dereuromark/cakephp-tools Class Usage Examples

Méthodes publiques

Méthode 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.

Méthodes protégées

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

Method Details

__construct() public méthode

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

_strftime() protected static méthode

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.
Résultat string formatted string with correct encoding.

age() public static méthode

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)
Résultat integer Age (0 if both timestamps are equal or empty, -1 on invalid dates)

ageBounds() public static méthode

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
Résultat array Array('min'=>$min, 'max'=>$max);

ageByHoroscope() public static méthode

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

ageByYear() public static méthode

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)
Résultat integer | string Age

ageRange() public static méthode

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
Résultat mixed

buildDefaultTime() public static méthode

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

buildTime() public static méthode

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
Résultat string Time

cWeek() public static méthode

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)
Résultat string

cWeekBeginning() public static méthode

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)
Résultat integer Timestamp

cWeekEnding() public static méthode

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)
Résultat integer Timestamp

cWeekMod() public static méthode

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

cWeeks() public static méthode

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)
Résultat integer Amount of weeks - 52 or 53

convertDate() public static méthode

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
Résultat string Formatted date

dayAsSql() public static méthode

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
Résultat string Partial SQL string.

dayName() public static méthode

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]
Résultat string translatedText

dayNames() public static méthode

Weekdays
public static dayNames ( array $dayKeys = [], array $options = [] ) : array
$dayKeys array
$options array
Résultat array

daysAsSql() public static méthode

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
Résultat string Partial SQL string.

daysInMonth() public static méthode

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

decimalToStandardTime() public static méthode

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
Résultat string

difference() public static méthode

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
Résultat integer The distance in seconds

duration() public static méthode

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
Résultat string Time

fuzzy() public static méthode

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
Résultat string

fuzzyFromOffset() public static méthode

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
Résultat string text (i18n!)

getGmtOffset() public méthode

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
Résultat integer Offset in hours

hasDaylightSavingTime() public méthode

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
Résultat boolean

incrementDate() public méthode

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
Résultat object DateTime with incremented/decremented month/year values.

isDayAfterTomorrow() public static méthode

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
Résultat boolean True if datetime string is day after tomorrow

isInRange() public static méthode

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

isInTheFuture() public static méthode

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
Résultat boolean True if datetime is not today AND is in the future

isNotTodayAndInTheFuture() public static méthode

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
Résultat boolean True if datetime is not today AND is in the future

lengthOfTime() public static méthode

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
Résultat string

localDate() public static méthode

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
Résultat string

monthName() public static méthode

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)
Résultat string translatedText

monthNames() public static méthode

Months
public static monthNames ( array $monthKeys = [], array $options = [] ) : array
$monthKeys array
$options array
Résultat array

niceDate() public static méthode

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
Résultat string

niceTime() public static méthode

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

pad() public static méthode

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

parseLocalDate() public static méthode

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
Résultat integer Seconds

parseLocalTime() public static méthode

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
Résultat integer Seconds

parseLocalizedDate() public static méthode

.. - 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
Résultat string timestamp

period() public static méthode

.. 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)
Résultat array period [0=>min, 1=>max]

periodAsSql() public static méthode

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)
Résultat string query SQL Query

relLengthOfTime() public static méthode

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
Résultat string

standardToDecimalTime() public static méthode

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

timezoneByCoordinates() public static méthode

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
Résultat DateTimeZone Timezone object

tzOffset() public static méthode

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

wasDayBeforeYesterday() public static méthode

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
Résultat boolean True if datetime string was day before yesterday