1

I am new in PHP and Learning to convert datetime in different format I have date time like this

My Date Input is like

03/12/2020 23:18

Which I need like

 2020-12-03 23:18:00

So I am trying like

$date = date('Y-m-d H:i:s', strtotime($appointment_date));

But its giving me date like

1970-01-01 00:00:00

Let me know if anyone here can help me for solve the issue. Thanks!

ADyson
  • 57,178
  • 14
  • 51
  • 63
Riya Shah
  • 155
  • 1
  • 12
  • Please show your exact code. [I cannot duplicate the issue](https://3v4l.org/7778c) – aynber Dec 30 '20 at 17:55
  • @aynber Sorry, I have edited question. Thanks! – Riya Shah Dec 30 '20 at 17:58
  • 1
    So you want it to be interpreted as dd/mm/yyyy rather than mm/dd/yyyy? PHP has no way of knowing which format you are using. It assumes mm/dd/yyyy by default. By the way, that code doesn't produce the output you're claiming - it produces 12th Match instead of 3rd December - https://3v4l.org/qe5O2. Use DateTime::createFromFormat to parse the date, then you can specify the incoming format – ADyson Dec 30 '20 at 18:03

1 Answers1

4

You could use the DateTime format method:

$incoming_date = '12/12/2020 23:18';
$date = DateTime::createFromFormat('d/m/Y H:i:s', $incoming_date . ':00');
$outgoing_date = $date->format('Y-m-d H:i:s');

I'm about 95% sure you can also leave off the seconds, but I can't say for sure without testing it:

$incoming_date = '12/12/2020 23:18';
$date = DateTime::createFromFormat('d/m/Y H:i', $incoming_date);
$outgoing_date = $date->format('Y-m-d H:i:s');
Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30