summaryrefslogtreecommitdiff
path: root/src/Timestamp.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/Timestamp.php')
-rw-r--r--src/Timestamp.php38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/Timestamp.php b/src/Timestamp.php
new file mode 100644
index 0000000..a23ba13
--- /dev/null
+++ b/src/Timestamp.php
@@ -0,0 +1,38 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Zhineng\Snowflake;
+
+final class Timestamp extends Field
+{
+ use Makable;
+
+ /**
+ * The epoch in milliseconds.
+ */
+ public readonly int $epoch;
+
+ public function __construct(
+ string $name = 'timestamp',
+ int $bits = 41,
+ \DateTime|int|null $epoch = null
+ ) {
+ parent::__construct($name, $bits);
+
+ $this->epoch = $epoch instanceof \DateTime
+ ? $epoch->getTimestamp() * 1000
+ : ($epoch ?? 0);
+
+ if ($this->epoch < 0) {
+ throw new \InvalidArgumentException('Epoch must be non-negative.');
+ }
+ }
+
+ public function value(): int
+ {
+ $now = (int) floor(microtime(as_float: true) * 1000);
+
+ return $now - $this->epoch;
+ }
+}