2017-05-21 21:16:32 +00:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace JKingWeb\Arsse\Misc;
|
|
|
|
|
2017-07-17 11:47:57 +00:00
|
|
|
class Date {
|
2017-05-21 21:16:32 +00:00
|
|
|
|
2017-07-17 11:47:57 +00:00
|
|
|
static function transform($date, string $outFormat = null, string $inFormat = null, bool $inLocal = false) {
|
|
|
|
$date = self::normalize($date, $inFormat, $inLocal);
|
2017-07-21 02:40:09 +00:00
|
|
|
if(is_null($date) || is_null($outFormat)) {
|
|
|
|
return $date;
|
|
|
|
}
|
2017-07-07 19:25:47 +00:00
|
|
|
$outFormat = strtolower($outFormat);
|
2017-07-21 02:40:09 +00:00
|
|
|
if($outFormat=="unix") {
|
|
|
|
return $date->getTimestamp();
|
|
|
|
}
|
2017-07-07 19:25:47 +00:00
|
|
|
switch ($outFormat) {
|
2017-05-21 21:16:32 +00:00
|
|
|
case 'http': $f = "D, d M Y H:i:s \G\M\T"; break;
|
2017-07-09 22:31:03 +00:00
|
|
|
case 'iso8601': $f = "Y-m-d\TH:i:s"; break;
|
2017-05-21 21:16:32 +00:00
|
|
|
case 'sql': $f = "Y-m-d H:i:s"; break;
|
|
|
|
case 'date': $f = "Y-m-d"; break;
|
|
|
|
case 'time': $f = "H:i:s"; break;
|
2017-07-07 19:25:47 +00:00
|
|
|
default: $f = $outFormat; break;
|
2017-05-21 21:16:32 +00:00
|
|
|
}
|
2017-07-07 19:25:47 +00:00
|
|
|
return $date->format($f);
|
2017-05-21 21:16:32 +00:00
|
|
|
}
|
|
|
|
|
2017-07-17 11:47:57 +00:00
|
|
|
static function normalize($date, string $inFormat = null, bool $inLocal = false) {
|
2017-05-21 21:16:32 +00:00
|
|
|
if($date instanceof \DateTimeInterface) {
|
2017-07-07 19:25:47 +00:00
|
|
|
return $date;
|
2017-05-21 21:16:32 +00:00
|
|
|
} else if(is_numeric($date)) {
|
|
|
|
$time = (int) $date;
|
|
|
|
} else if($date===null) {
|
|
|
|
return null;
|
|
|
|
} else if(is_string($date)) {
|
2017-07-05 13:09:38 +00:00
|
|
|
try {
|
2017-07-07 19:25:47 +00:00
|
|
|
$tz = (!$inLocal) ? new \DateTimeZone("UTC") : null;
|
|
|
|
if(!is_null($inFormat)) {
|
|
|
|
switch($inFormat) {
|
|
|
|
case 'http': $f = "D, d M Y H:i:s \G\M\T"; break;
|
2017-07-09 22:31:03 +00:00
|
|
|
case 'iso8601': $f = "Y-m-d\TH:i:sP"; break;
|
2017-07-07 19:25:47 +00:00
|
|
|
case 'sql': $f = "Y-m-d H:i:s"; break;
|
|
|
|
case 'date': $f = "Y-m-d"; break;
|
|
|
|
case 'time': $f = "H:i:s"; break;
|
|
|
|
default: $f = $inFormat; break;
|
|
|
|
}
|
|
|
|
return \DateTime::createFromFormat("!".$f, $date, $tz);
|
|
|
|
} else {
|
|
|
|
return new \DateTime($date, $tz);
|
|
|
|
}
|
2017-07-05 13:09:38 +00:00
|
|
|
} catch(\Throwable $e) {
|
|
|
|
return null;
|
|
|
|
}
|
2017-05-21 21:16:32 +00:00
|
|
|
} else if (is_bool($date)) {
|
|
|
|
return null;
|
|
|
|
} else {
|
|
|
|
$time = (int) $date;
|
|
|
|
}
|
2017-07-15 17:33:17 +00:00
|
|
|
$tz = (!$inLocal) ? new \DateTimeZone("UTC") : null;
|
|
|
|
$d = new \DateTime("now", $tz);
|
2017-07-07 19:25:47 +00:00
|
|
|
$d->setTimestamp($time);
|
|
|
|
return $d;
|
2017-05-21 21:16:32 +00:00
|
|
|
}
|
|
|
|
}
|