6

I am getting date from system config using datepicker date format is dd/mm/yy

I want to convert it in to yy/mm/dd H:i:s and able to convert date in format: yy/mm/dd but time is not coming.

4 Answers 4

20

This way i convert date format

protected $timezone;

public function __construct(
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
......
)
{
    $this->timezone = $timezone;
}

$dateTimeZone = $this->timezone->date(new \DateTime($yourdate))->format('Y/m/d H:i:s');
3
  • $dateTimeZone = (new \DateTime($yourdate))->format('Y/m/d H:i:s'); will probably work too (without the timezone injection). Commented Nov 21, 2019 at 0:33
  • 1
    You asked the question, and you answered it. Then you put a comment for yourself to accept the answer? Commented Sep 21, 2020 at 15:12
  • It's not working when your timezone is different, this solution works well: magento.stackexchange.com/a/372331/82670
    – Msquare
    Commented Feb 27 at 10:15
3

In PHP, you can convert date to any format by using a combination of date and strtotime function.

Please try below format to convert date:

date(format, strtotime(originaldate))

Suppose, you have original date as mm/dd/yy (say 21/03/10) and you want to convert it to yy/mm/dd H:i:s format (say 10/03/21 00:00:00), then try below code:

$originalDate = "21/03/10";

$newDate = date("d-m-Y H:i:s", strtotime($originalDate));

1
  • 1
    @ Mohit Kumar Arora your solution is not work...! Commented Aug 25, 2017 at 5:37
1

Please try the code

protected $date;

public function __construct(
    \Magento\Framework\Stdlib\DateTime\TimezoneInterface $date
) {
        $this->date =  $date;
}

public function getFormatedDate($yourdate)
{
    $yourdate = "2022-10-09 06:00:00";
    return $this->date->date(strtotime($yourdate))->format('Y-m-d H:i:s');
}
0

Try this,

 public function __construct(
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $date
  ){
        $this->date =  $date;
  }

  public function getTimeconverter($yourdate)
    {
        return $this->date->date($yourdate)->format('Y-m-d H:i:s');
    }

Thanks!!

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.