The following piece of code:
<?= $post->getCreatedAt() ?>
Returns the following output: 2018-04-13 11:53:00
How to adjust that piece of code in a way that the output would be something like '13 April'?
Simplest Solution:
Although, this is likely violating coding standards...
echo \Magento\Framework\App\ObjectManager::getInstance()
->create(\Magento\Framework\Intl\DateTimeFactory::class)
->create($post->getCreatedAt(), new \DateTimeZone('America/New_York')) // Update timezone, for example use from config
->format('d F');
Solution:
You could try do this below, but I think you should be sure to follow Magento2 coding standards..
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$timezone = $obj->create(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class);
$dt = $timezone->formatDateTime(
$post->getCreatedAt(),
null,
null,
null,
$timezone->getConfigTimezone(),
'd LLLL'
);
\Zend_Debug::dump($dt);
Output:
...vendor\magento\zendframework1\library\Zend\Debug.php:82:string '13 April' (length=8)
For the pattern, follow this: http://userguide.icu-project.org/formatparse/datetime
Review of Usage in Magento Code:
Review how Magento does it: ./vendor/magento/module-checkout/Helper/Data.php
:
in __construct(
we have \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
and $this->_localeDate = $localeDate
Then the class is used with the formatDateTime(...) member function:
'dateAndTime' => $this->_localeDate->formatDateTime(
new \DateTime(),
\IntlDateFormatter::MEDIUM,
\IntlDateFormatter::MEDIUM
),
Review of the function definition:
/**
* @param string|\DateTimeInterface $date
* @param int $dateType
* @param int $timeType
* @param null $locale
* @param null $timezone
* @param string|null $pattern
* @return string
*/
public function formatDateTime(
$date,
$dateType = \IntlDateFormatter::SHORT,
$timeType = \IntlDateFormatter::SHORT,
$locale = null,
$timezone = null,
$pattern = null
) {
if (!($date instanceof \DateTimeInterface)) {
$date = new \DateTime($date);
}
if ($timezone === null) {
if ($date->getTimezone() == null || $date->getTimezone()->getName() == 'UTC'
|| $date->getTimezone()->getName() == '+00:00'
) {
$timezone = $this->getConfigTimezone();
} else {
$timezone = $date->getTimezone();
}
}
$formatter = new \IntlDateFormatter(
$locale ?: $this->_localeResolver->getLocale(),
$dateType,
$timeType,
$timezone,
null,
$pattern
);
return $formatter->format($date);
}
Usage in Magento Tests:
$invoiceCreatedAt = $order->getInvoiceCollection()
->getFirstItem()
->getCreatedAt();
/** @var \Magento\Framework\Stdlib\DateTime\DateTime $dateTime */
$dateTime = $this->objectManager->create(\Magento\Framework\Stdlib\DateTime\DateTimeFactory::class)
->create();
/** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */
$timezone = $this->objectManager->create(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class);
$invoiceCreatedAt = $timezone->formatDateTime(
$invoiceCreatedAt,
\IntlDateFormatter::SHORT,
\IntlDateFormatter::NONE,
null,
null,
'yyyy-MM-dd'
);
$invoiceCreatedAtDate = $dateTime->date('Y-m-d', $invoiceCreatedAt);
Abstract Block
To use in views, the block is inheriting from the abstract, which contains methods that take into account international formats ... Why would you want to change something like this to support only a fixed format, rather than a format applicable to whichever region is configured within the system config?
Review: vendor/magento/framework/View/Element/AbstractBlock.php
,
It has the following code:
/**
* Retrieve formatting date
*
* @param null|string|\DateTimeInterface $date
* @param int $format
* @param bool $showTime
* @param null|string $timezone
* @return string
*/
public function formatDate(
$date = null,
$format = \IntlDateFormatter::SHORT,
$showTime = false,
$timezone = null
) {
$date = $date instanceof \DateTimeInterface ? $date : new \DateTime($date);
return $this->_localeDate->formatDateTime(
$date,
$format,
$showTime ? $format : \IntlDateFormatter::NONE,
null,
$timezone
);
}
/**
* Retrieve formatting time
*
* @param \DateTime|string|null $time
* @param int $format
* @param bool $showDate
* @return string
*/
public function formatTime(
$time = null,
$format = \IntlDateFormatter::SHORT,
$showDate = false
) {
$time = $time instanceof \DateTimeInterface ? $time : new \DateTime($time);
return $this->_localeDate->formatDateTime(
$time,
$showDate ? $format : \IntlDateFormatter::NONE,
$format
);
}
Another example in the framework:
Now check out this class that has been created in vendor/magento/framework/Data/Form/Element/Date.php
:
/**
* Get date value as string.
* Format can be specified, or it will be taken from $this->getFormat()
*
* @param string $format (compatible with \DateTime)
* @return string
*/
public function getValue($format = null)
{
if (empty($this->_value)) {
return '';
}
if (null === $format) {
$format = $this->getDateFormat();
$format .= ($format && $this->getTimeFormat()) ? ' ' : '';
$format .= $this->getTimeFormat() ? $this->getTimeFormat() : '';
}
return $this->localeDate->formatDateTime(
$this->_value,
null,
null,
null,
$this->_value->getTimezone(),
$format
);
}
Try this:
<?php
$createdAt = $post->getCreatedAt();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$timezoneInterface = $objectManager->get('Magento\Framework\Stdlib\DateTime\TimezoneInterface');
$createdAt = $timezoneInterface->date($createdAt)->format('d F Y');
?>
<?php echo $createdAt; ?>
OR
Inject \Magento\Framework\Stdlib\DateTime\TimezoneInterface
in our constructor:
Add below code in your Block or Model or Controller file
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
*/
public function __construct(
...
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface
...
) {
...
$this->timezoneInterface = $timezoneInterface;
...
}
public function dateFormat($createdAt, $dateFormat = 'd F Y')
{
return $this->timezoneInterface->date($createdAt)->format($dateFormat);
}
Use it in your .phtml file like so:
<?php echo $block->dateFormat($post->getCreatedAt(), 'd F Y'); ?>
After that, run the below command and check
php bin/magento setup:di:compile
Shorter solution, not sure if it works with 2.2.3 but it work with 2.3 +:
$date = new DateTime($post->getCreatedAt());
$dateFormatted = $date->format('d F');