0

I have a datepicker in my site which formats the time in the current locale. So the time gets sent to the server in d/MM/yy-format.

The locale on the frontend is determined by Magento\Framework\Stdlib\DateTime\TimezoneInterface::getDateFormat().

Now how can I convert this date to a database-friendly datetime (YYYY-MM-DD) or at least to a timestamp of some sort?

So basically I'm looking for a clean generic approach on how to convert a localized date to a timestamp.

I've tried all kind of things but none seemed to work.

1

Found the answer to my own question:

/**
 * @var \Magento\Framework\Locale\ResolverInterface
 */
protected $localeResolver;

... some code ...

$newDate = date('Y-m-d', (new \IntlDateFormatter(
    $this->localeResolver->getLocale(),
    \IntlDateFormatter::SHORT,
    \IntlDateFormatter::NONE
))->parse($localizeDate));
| improve this answer | |
0

This work for me but directly using object manager is not a good way inject TimezoneInterface into your constructor:

 $date = "1991-12-19 00:00:00"
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $timezoneInterface = $objectManager->create('\Magento\Framework\Stdlib\DateTime\TimezoneInterface');
 $formattedDate = $timezoneInterface->date($date)->format('Y/m/d');
| improve this answer | |
0

Magento 2 and 1 are all PHP based, you could use the native (quicker) PHP function to get this without having to add more into your __constructs or using ObjectManager (which can be heavy):

1) Get today's date formatted:

$todayDate = date("Y-m-d H:i:s");

2) Get a specific date formatted:

$MyDate = date_create("2020-04-08");

$MyDateFormatted = date_format($MyDate, "Y/m/d H:i:s");

I hope this helps.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.