Convert Date According to any Locale Magento 2: Sometimes we need to convert date format to locale, Today we will learn how to convert a date to a any locale.
So magento has an interface DateTimeFormatterInterface, through which we can convert a date to any other locale according to our need.
check the below code.
Using Dependency Injection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
namespace Webiators\CustomChanges\Model; class FormatDatLocale { private $timezoneInterface; public function __construct( \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface ) { $this->timezoneInterface = $timezoneInterface; } public function getFormatDate() { $staticDate = new \DateTime('2020-02-07'); $dateTimeFormatter = $this->timezoneInterface->formatDate( $staticDate, \IntlDateFormatter::FULL, 'en_GB' ); return $dateTimeFormatter; } } |
Using Object Manager:
1 2 3 4 5 6 7 8 9 10 11 12 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $dateTimeFormatter = $objectManager->get('Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterface'); $staticDate = new \DateTime('2020-02-07'); /** * Returns a translated and localized date string * * @param \IntlCalendar|\DateTime $object * @param string|int|array|null $format * @param string|null $locale * @return string */ $convertedDate = $dateTimeFormatter->formatObject($staticDate, \IntlDateFormatter::FULL, 'en_GB'); |
Feel free to put forward any doubts in the Comments section. I’d be happy to help!
Hit 5 Stars if you find this post helpful
0 (based on 0 Reviews)