PHP Класс Tools\Utility\Time

Наследование: extends Cake\I18n\Time
Показать файл Открыть проект Примеры использования класса

Открытые методы

Метод Описание
__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.

Защищенные методы

Метод Описание
_strftime ( string $format, integer $date ) : string Multibyte wrapper for strftime.

Описание методов

__construct() публичный Метод

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

_strftime() защищенный статический Метод

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.
Результат string formatted string with correct encoding.

age() публичный статический Метод

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)
Результат integer Age (0 if both timestamps are equal or empty, -1 on invalid dates)

ageBounds() публичный статический Метод

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
Результат array Array('min'=>$min, 'max'=>$max);

ageByHoroscope() публичный статический Метод

Returns age by horoscope info.
public static ageByHoroscope ( integer $year, integer $sign ) : integer | array
$year integer Year
$sign integer Sign
Результат integer | array Age

ageByYear() публичный статический Метод

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)
Результат integer | string Age

ageRange() публичный статический Метод

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
Результат mixed

buildDefaultTime() публичный статический Метод

Return strings like 2:33:99 from seconds etc
public static buildDefaultTime ( integer $duration ) : string
$duration integer Duration in seconds
Результат string Time

buildTime() публичный статический Метод

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".
Устаревший: 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
Результат string Time

cWeek() публичный статический Метод

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)
Результат string

cWeekBeginning() публичный статический Метод

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)
Результат integer Timestamp

cWeekEnding() публичный статический Метод

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)
Результат integer Timestamp

cWeekMod() публичный статический Метод

0=sunday to 7=saturday (default)
public static cWeekMod ( integer $num ) : integer
$num integer Number of day.
Результат integer Days since the start of the week.

cWeeks() публичный статический Метод

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)
Результат integer Amount of weeks - 52 or 53

convertDate() публичный статический Метод

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
Результат string Formatted date

dayAsSql() публичный статический Метод

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
Результат string Partial SQL string.

dayName() публичный статический Метод

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]
Результат string translatedText

dayNames() публичный статический Метод

Weekdays
public static dayNames ( array $dayKeys = [], array $options = [] ) : array
$dayKeys array
$options array
Результат array

daysAsSql() публичный статический Метод

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
Результат string Partial SQL string.

daysInMonth() публичный статический Метод

Return the days of a given month.
public static daysInMonth ( integer $year, integer $month ) : string
$year integer
$month integer
Результат string Days

decimalToStandardTime() публичный статический Метод

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
Результат string

difference() публичный статический Метод

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
Результат integer The distance in seconds

duration() публичный статический Метод

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
Результат string Time

fuzzy() публичный статический Метод

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
Результат string

fuzzyFromOffset() публичный статический Метод

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
Результат string text (i18n!)

getGmtOffset() публичный Метод

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
Результат integer Offset in hours

hasDaylightSavingTime() публичный Метод

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
Результат boolean

incrementDate() публичный Метод

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
Результат object DateTime with incremented/decremented month/year values.

isDayAfterTomorrow() публичный статический Метод

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
Результат boolean True if datetime string is day after tomorrow

isInRange() публичный статический Метод

For birthdays etc
public static isInRange ( string $dateString, integer $seconds ) : boolean
$dateString string
$seconds integer
Результат boolean Success

isInTheFuture() публичный статический Метод

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
Результат boolean True if datetime is not today AND is in the future

isNotTodayAndInTheFuture() публичный статический Метод

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
Результат boolean True if datetime is not today AND is in the future

lengthOfTime() публичный статический Метод

Time length to human readable format.
См. также: 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
Результат string

localDate() публичный статический Метод

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
Результат string

monthName() публичный статический Метод

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)
Результат string translatedText

monthNames() публичный статический Метод

Months
public static monthNames ( array $monthKeys = [], array $options = [] ) : array
$monthKeys array
$options array
Результат array

niceDate() публичный статический Метод

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
Результат string

niceTime() публичный статический Метод

Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss
public static niceTime ( string $time ) : string
$time string
Результат string Time in format hh:mm

pad() публичный статический Метод

TimeLib::pad()
public static pad ( string $value, integer $length = 2, string $string = '0' ) : string
$value string
$length integer
$string string
Результат string

parseLocalDate() публичный статический Метод

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
Результат integer Seconds

parseLocalTime() публичный статический Метод

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
Результат integer Seconds

parseLocalizedDate() публичный статический Метод

.. - 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
Результат string timestamp

period() публичный статический Метод

.. 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)
Результат array period [0=>min, 1=>max]

periodAsSql() публичный статический Метод

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)
Результат string query SQL Query

relLengthOfTime() публичный статический Метод

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
Результат string

standardToDecimalTime() публичный статический Метод

Hours, minutes e.g. 9.3 => 9.5
public static standardToDecimalTime ( integer $value ) : float
$value integer
Результат float

timezoneByCoordinates() публичный статический Метод

Gets the timezone that is closest to the given coordinates
Устаревший: Would need Geo plugin to work
public static timezoneByCoordinates ( float $lat, float $lng ) : DateTimeZone
$lat float
$lng float
Результат DateTimeZone Timezone object

tzOffset() публичный статический Метод

EXPERIMENTAL!!!
public static tzOffset ( integer $gmtoffset, boolean $isDst ) : integer
$gmtoffset integer Offset in seconds
$isDst boolean If DST
Результат integer offset Calculated offset

wasDayBeforeYesterday() публичный статический Метод

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
Результат boolean True if datetime string was day before yesterday