Skip to content

Commit

Permalink
Support passing floating point numbers to constructor, setting micros…
Browse files Browse the repository at this point in the history
…econds
  • Loading branch information
thekid committed Aug 17, 2024
1 parent a8d7420 commit 754b663
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/main/php/util/Date.class.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php namespace util;

use DateTime;
use lang\{IllegalArgumentException, IllegalStateException, Value};

/**
Expand Down Expand Up @@ -36,19 +37,21 @@ static function __static() {
* - If no timezone has been given as second parameter, the system's default
* timezone is used.
*
* @param ?int|string|php.DateTime $in
* @param ?int|float|string|DateTime $in
* @param ?util.TimeZone $timezone default NULL string of timezone
* @throws lang.IllegalArgumentException in case the date is unparseable
*/
public function __construct($in= null, ?TimeZone $timezone= null) {
if ($in instanceof \DateTime) {
if (null === $in) {
$this->handle= date_create('now', $timezone ? $timezone->getHandle() : null);
} else if ($in instanceof DateTime) {
$this->handle= $in;
} else if ((string)(int)$in === (string)$in) {
} else if (is_int($in) || is_float($in) || (string)(int)$in === $in) {

// Specially mark timestamps for parsing (we assume here that strings
// containing only digits are timestamps)
$this->handle= date_create('@'.$in);
date_timezone_set($this->handle, $timezone ? $timezone->getHandle() : timezone_open(date_default_timezone_get()));
$timezone && date_timezone_set($this->handle, $timezone->getHandle());
} else {
if (false === ($this->handle= date_create($in ?? 'now', $timezone ? $timezone->getHandle() : null))) {
throw new IllegalArgumentException('Given argument is neither a timestamp nor a well-formed timestring: '.Objects::stringOf($in));
Expand All @@ -62,7 +65,7 @@ public function hashCode(): string {
}

/** Retrieve handle of underlying DateTime object. */
public function getHandle(): \DateTime {
public function getHandle(): DateTime {
return clone $this->handle;
}

Expand Down
5 changes: 5 additions & 0 deletions src/test/php/util/unittest/DateTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -358,4 +358,9 @@ public function testInvalidUnixTimestamp() {
public function microseconds() {
Assert::equals(393313, (new Date('2019-07-03 15:18:10.393313'))->getMicroSeconds());
}

#[Test]
public function float_timestamp() {
Assert::equals(393000, (new Date(1723896922.393))->getMicroSeconds());
}
}

0 comments on commit 754b663

Please sign in to comment.