Skip to content

Commit

Permalink
Implement ZonedDateTime::fromDateTime()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Mar 14, 2018
1 parent dccebea commit 7ab2cc3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/ZonedDateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,37 @@ public static function parse(string $text, DateTimeParser $parser = null) : Zone

return ZonedDateTime::from($parser->parse($text));
}
/**
* Creates a ZonedDateTime from a native DateTime object.
*
* @param \DateTimeInterface $dateTime
*
* @return ZonedDateTime
*
* @throws DateTimeException If the DateTime object has no timezone.
*/
public static function fromDateTime(\DateTimeInterface $dateTime) : ZonedDateTime
{
$localDateTime = LocalDateTime::fromDateTime($dateTime);

$dateTimeZone = $dateTime->getTimezone();

if ($dateTimeZone === false) {
throw new DateTimeException('This DateTime object has no timezone.');
}

$timeZone = TimeZone::fromDateTimeZone($dateTimeZone);

if ($timeZone instanceof TimeZoneOffset) {
$timeZoneOffset = $timeZone;
} else {
$timeZoneOffset = TimeZoneOffset::ofTotalSeconds($dateTime->getOffset());
}

$instant = Instant::of($dateTime->getTimestamp(), $localDateTime->getNano());

return new ZonedDateTime($localDateTime, $timeZoneOffset, $timeZone, $instant);
}

/**
* Returns the `LocalDateTime` part of this `ZonedDateTime`.
Expand Down
25 changes: 25 additions & 0 deletions tests/ZonedDateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,31 @@ public function providerParseInvalidStringThrowsException() : array
];
}

/**
* @dataProvider providerFromDateTime
*
* @param string $dateTimeString
* @param string $timeZone
* @param string $expected
*/
public function testFromDateTime(string $dateTimeString, string $timeZone, string $expected)
{
$dateTime = new \DateTime($dateTimeString, new \DateTimeZone($timeZone));
$this->assertIs(ZonedDateTime::class, $expected, ZonedDateTime::fromDateTime($dateTime));
}

/**
* @return array
*/
public function providerFromDateTime() : array
{
return [
['2018-07-21 14:09:10.23456', 'America/Los_Angeles', '2018-07-21T14:09:10.23456-07:00[America/Los_Angeles]'],
['2019-01-21 17:59', 'America/Los_Angeles', '2019-01-21T17:59-08:00[America/Los_Angeles]'],
['2019-01-23 09:10:11.123', '+05:30', '2019-01-23T09:10:11.123+05:30'],
];
}

public function testChangeTimeZone()
{
$timezone1 = TimeZone::parse('UTC');
Expand Down

0 comments on commit 7ab2cc3

Please sign in to comment.