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.
Asked
Active
Viewed 45 times
-1
-
3[$date = `DateTime::createFromFormat( 'dmy', '290416' )->format( 'd/m/y' )`](http://php.net/manual/en/datetime.createfromformat.php) – fusion3k Apr 29 '16 at 22:52
-
1@fusion3k you should post this as an answer - it's correct. – Kevin Lynch Apr 29 '16 at 22:58
-
yeah it worked thanks a lot @fusion3k you can post as your answer. – user2999752 Apr 29 '16 at 23:03
2 Answers
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