diff --git a/src/Type/DateTimeValue.php b/src/Type/DateTimeValue.php index 763e201..a6b14e7 100644 --- a/src/Type/DateTimeValue.php +++ b/src/Type/DateTimeValue.php @@ -4,6 +4,7 @@ namespace SimpleSAML\XML\Type; +use DateTimeInterface; use SimpleSAML\XML\Assert\Assert; use SimpleSAML\XML\Exception\SchemaViolationException; @@ -15,6 +16,9 @@ */ class DateTimeValue extends AbstractValueType { + public const string DATETIME_FORMAT = 'Y-m-d\\TH:i:sP'; + + /** * Sanitize the value. * @@ -38,4 +42,14 @@ protected function validateValue(string $value): void { Assert::validDateTime($this->sanitizeValue($value), SchemaViolationException::class); } + + + /** + * @param \DateTimeInterface $value + * @return static + */ + public static function fromDateTime(DateTimeInterface $value): static + { + return new static($value->format(static::DATETIME_FORMAT)); + } } diff --git a/tests/Type/DateTimeValueTest.php b/tests/Type/DateTimeValueTest.php index 47ded07..50fb068 100644 --- a/tests/Type/DateTimeValueTest.php +++ b/tests/Type/DateTimeValueTest.php @@ -4,6 +4,7 @@ namespace SimpleSAML\Test\XML\Type; +use DateTimeImmutable; use PHPUnit\Framework\Attributes\{CoversClass, DataProvider}; use PHPUnit\Framework\TestCase; use SimpleSAML\XML\Exception\SchemaViolationException; @@ -57,4 +58,16 @@ public static function provideDateTime(): array 'wrong format' => [false, '01-10-26T21:32'], ]; } + + + /** + * Test the fromDateTime function + */ + public function testFromDateTime(): void + { + $dt = new DateTimeImmutable('@946684800'); + + $dateTimeValue = DateTimeValue::fromDateTime($dt); + $this->assertEquals('2000-01-01T00:00:00+00:00', $dateTimeValue->getValue()); + } }