- Removed default page setting based on query params adn - Added DateTime format doc
71 lines
2.0 KiB
PHP
71 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\Entity\Field;
|
|
|
|
trait DatetimeTrait
|
|
{
|
|
public string $format = "Y-m-d H:i:s";
|
|
|
|
public function load(mixed ...$arguments)
|
|
{
|
|
$value = $arguments[0];
|
|
|
|
try {
|
|
# From Timestamp
|
|
if ( is_numeric($value) ) {
|
|
$obj = new static("@$value");
|
|
}
|
|
else {
|
|
$obj = new static($value);
|
|
}
|
|
}
|
|
catch(\Throwable $ex) {
|
|
throw new \Exception(sprintf("An error occured trying to instanciate from '%s'. %s", $value, $ex->getMessage()), $ex->getCode(), $ex);
|
|
}
|
|
|
|
return $obj;
|
|
}
|
|
|
|
public function setTime($hour, $minute, $second = 0, $microsecond = 0) : \DateTime
|
|
{
|
|
$fromParent = parent::setTime($hour, $minute, $second, $microsecond);
|
|
|
|
return new static($fromParent);
|
|
}
|
|
|
|
public function save()
|
|
{
|
|
return $this->__toString();
|
|
}
|
|
|
|
public function __toString()
|
|
{
|
|
return $this->format($this->format);
|
|
}
|
|
|
|
#[\Deprecated]
|
|
public function formatLocale(string $format) : string
|
|
{
|
|
return strftime($format, $this->getTimestamp());
|
|
}
|
|
|
|
# patterns: https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table
|
|
# see also 100-datetime-format.md file in DOC
|
|
public function formatLocaleIntl(int $dateFormatter = \IntlDateFormatter::LONG, int $timeFormatter = \IntlDateFormatter::NONE, ? string $pattern = null) : string
|
|
{
|
|
$formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormatter, $timeFormatter, \date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, $pattern);
|
|
|
|
return $formatter->format($this->getTimestamp());
|
|
}
|
|
|
|
public function ageAt(null|\DateTime $dateTime) : int
|
|
{
|
|
return (int) (( (int) ($dateTime ?: new DateTime())->format('Ymd') - (int) $this->format('Ymd') ) / 10000);
|
|
}
|
|
|
|
public function jsonSerialize(): mixed
|
|
{
|
|
return $this;
|
|
}
|
|
}
|