I'd like to create PHP \DateTime object from negative UNIX timestamps (before 1970) with microseconds without much dirty code.
new \DateTime("@-100")
works, but new \DateTime("@-100.123")
does not.
\DateTime::createFromFormat("U u", "100 123456")
works, but \DateTime::createFromFormat("U u", "-100 123456")
does not.
And \DateInterval does not have microseconds currently.
The only way I've found so far to create such DateTime is parsing of strings like new \DateTime("1969-12-31T23:59:59.877GMT")
but I don't like number->string->DateTime chain. Is there more clear way?
The code that works on x64 for conversion to and from microseconds, but I don't like it much.
$ts_mks = -100000012345;
$div = floor($ts_mks / 1000000);
$mod = $ts_mks % 1000000;
if($mod < 0) {
$mod += 1000000;
}
$date_s = new \DateTime();
$date_s->setTimestamp($div);
$date_s->setTimezone(new \DateTimeZone("GMT"));
$ts_str = $date_s->format("Y-m-d\\TH:i:s.") . sprintf("%06dZ", $mod);
// result
$date = \DateTime::createFromFormat("Y-m-d\\TH:i:s.ue", $ts_str);
Mush shorter but more cryptic (combining integer negative secons with positive fractional part):
$date = new \DateTime(sprintf("@%d 00:00:00.%06d", $div, $mod));
Conversion back
$ts_mks = $date->getTimestamp() * 1000000 + (int) $date->format("u");