-2

I need to convert date format in php , But i am getting getting error

here is my code

 $test = new DateTime('23/09/2016');
   echo date_format($test, 'Y-m-d');

But i am getting error as

Message: DateTime::__construct(): Failed to parse time string (23/09/2016) at position 0 (2): Unexpected character 

How to resolve the issue

vellai durai
  • 1,019
  • 3
  • 16
  • 38

4 Answers4

0

You're not telling DateTime that what's your string date format. So, it's unable to create a DateTime object.

This should work :

$test = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($test, 'Y-m-d');

Read more about createFromFormat here.

Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
0

Use createFromFormat instead. Like this,

$date = DateTime::createFromFormat('d/m/Y', '23/09/2016');
echo date_format($date, 'Y-m-d');

It's throwing exception because it's unable to parse String to date with / in it.

http://php.net/manual/en/datetime.createfromformat.php

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

You are getting error because your code is not match with Years and Day. If you write code below it will work.I just exchange between Years and days .

 $test = new DateTime('2016/09/23');
 echo date_format($test, 'Y-m-d');

Or you can use createFromFormat to format first date string then convert it in your required format.

Chonchol Mahmud
  • 2,717
  • 7
  • 39
  • 72
0
$input = "23/09/2016";
$arr = explode("/", $input);
#   mktime is a function to create timestamp
#   mktime (hour, min, sec, month, day, year)
$mktime = mktime(0,0,0,(int) $arr[1],(int)$arr[0],(int)$arr[2]);
$date1 = date ('d/m/Y', $mktime);
$date2 = date ('Y/m/d', $mktime);

echo "input: $input\ndate1: $date1\ndate2: $date2\n";

or you can try this one, $date2 is the final result.