-1

I need to convert string value "290416" which is actually date but not in correct format. I need to change it in date format like 29/04/16. please help.

user2999752
  • 63
  • 1
  • 1
  • 4

2 Answers2

0

The most robust way will be to use createFromFormat, passing in your format and the string, and they you have a DateTime object and can do many things with it.

define('MY_DATE_INPUT_FORMAT', 'mdy');
define('MY_DATE_OUTPUT_FORMAT', 'm/d/y');
$inputDateString = '042916';
$dateObj = DateTime::createFromFormat(MY_DATE_INPUT_FORMAT, $inputDateString);
$outputString = $dateObj->format(MY_DATE_OUTPUT_FORMAT);

This can also be done procedurally:

$date = date_create_from_format(MY_DATE_INPUT_FORMAT, $inputDateString);
echo date_format($date, MY_DATE_OUTPUT_FORMAT);
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
0

If you don't need it as a date but only in date format. Meaning you are not performing any date-functions on it but just displaying it as a date you could use

$str = '290416';
$arr = str_split($str, 2);
$date_string = $implode('/', $arr);
RST
  • 3,899
  • 2
  • 20
  • 33
  • thanks it also worked. but $datet = DateTime::createFromFormat( 'dmy', '290416' )->format( 'd/m/y' ); also worked – user2999752 Apr 29 '16 at 23:05