Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Last active March 15, 2018 08:13
Show Gist options
  • Save BenMorel/38581399d47a2bb52b60bb9e06ecf405 to your computer and use it in GitHub Desktop.
Save BenMorel/38581399d47a2bb52b60bb9e06ecf405 to your computer and use it in GitHub Desktop.
<?php
use Brick\DateTime\LocalDate;
use Brick\DateTime\LocalTime;
use Brick\DateTime\LocalDateTime;
/**
* Formatter for date-time classes.
*/
class DateTimeFormatter
{
/**
* @param LocalDate $date
* @param string $locale
*
* @return string
*/
public function formatLocalDate(LocalDate $date, string $locale) : string
{
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
$formatter->setTimeZone('UTC');
$datetime = new \DateTime(null, new \DateTimeZone('UTC'));
$datetime->setDate($date->getYear(), $date->getMonth(), $date->getDay());
return $formatter->format($datetime);
}
/**
* @todo only supports HH:MM right now. Automatically switch between HH:MM & HH:MM:SS depending on SS==00?
* @todo same for nanos?
*
* @param LocalTime $time
* @param string $locale
*
* @return string
*/
public function formatLocalTime(LocalTime $time, string $locale) : string
{
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
$formatter->setTimeZone('UTC');
$datetime = new \DateTime(null, new \DateTimeZone('UTC'));
$datetime->setTime($time->getHour(), $time->getMinute(), $time->getSecond());
return $formatter->format($datetime);
}
/**
* @param LocalDateTime $dateTime
* @param string $locale
*
* @return string
*/
public function formatLocalDateTime(LocalDateTime $dateTime, string $locale) : string
{
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT);
$formatter->setTimeZone('UTC');
$datetime = new \DateTime((string) $dateTime, new \DateTimeZone('UTC'));
return $formatter->format($datetime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment