0

I have been doing this in Magento 1 to save my local date like this:

//in my custom controller
$data = $this->_filterDateTime($this->getRequest()->getPost('my_name'), array("date"));

Now, is there similar way to do this in Magento 2?

What I have done so far:

//in constructor 
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timeZoneInterface,
\Magento\Framework\Stdlib\DateTime $dateTime,

$this->_timeZone = $timeZoneInterface;
$this->dateTime = $dateTime;


/////////////
//in my function
/////////////

//format d/m/y
//timezone Australia/Sydney
$date = $this->dateTime->formatDate(('17/08/18 2:16:35 pm');

//this also didn't work
$date = $this->_timeZone->convertConfigTimeToUtc('17/08/18 2:16:35 pm');

Error thrown:

date. DateTime::__construct(): Failed to parse time string (17/08/18 2:16:35 pm) at position 0 (1): Unexpected character

If I change 17/08/18 2:16:35 pm to 12/08/18 2:16:35 pm then it works perfectly.

I am unable to tell Magento that my format is d/m/y.

1 Answer 1

2

I can see, M2 has similar function as M1 in controller class

//$this->dateTimeFilter is \Magento\Framework\Stdlib\DateTime\Filter\DateTime
protected function _filterPostData($data)
{
    $inputFilter = new \Zend_Filter_Input(
            ['my_date_field' => $this->dateTimeFilter],
            [],
            $data
    );
    $data = $inputFilter->getUnescaped();
    return $data;
}

However, this was working with Date but not the time. It always saved my AEST time as UTC, which is why while doing $block->formatTime($myDate, \IntlDateFormatter::MEDIUM) gave me wrong time, ie. 10+ hours.

I am sure I am still missing something here. Would love to know more on this.

Although, for time being, I am able to save it like this:

$this->_timeZone->convertConfigTimeToUtc($object->getMyDateField(), 'm/d/Y h:i:s a');

I was missing 'm/d/Y h:i:s a' part, while I posted my qst.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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