0

I have tried to convert following date to mysql date format

accutual my date is : 01-01-17

PHP Code

<?php

$datesrc =  '01-01-17';

echo date('Y-m-d', strtotime($datesrc));

?>

Result:

2001-01-17

In this case how to handle this type of date format(01-01-17 (d-m-y)), because i got this date format in user uploaded file..

Balakumar B
  • 770
  • 5
  • 17
  • 41
  • MySQL date's format is Y-m-d – Raymond Nijland Jul 28 '17 at 11:16
  • `$old_date = '01-01-17' ; // returns Saturday, January 30 10 02:06:34 $old_date_timestamp = strtotime($old_date); $new_date = date('Y-m-d H:i:s', $old_date_timestamp); echo $new_date;` Result: `2001-01-17 00:00:00` @Paul Crovella – Balakumar B Jul 28 '17 at 11:23
  • validate user to specific format . Even if we give a solution for this in future the user may upload yy-mm-dd then it will mess up. – Abid Jul 28 '17 at 11:30
  • $date = DateTime::createFromFormat('d/m/y', "01/01/17"); echo $date->format('Y-m-d'); – Abid Jul 28 '17 at 11:35

2 Answers2

0
<?php 
$dateString = '01-01-17';
$myDateTime = DateTime::createFromFormat('d-m-y', $dateString);
$newDateString = $myDateTime->format('Y-m-d');

echo $newDateString;

?>

You can do it like this. First use the DateTime::createFormat to create a DateTime instance of the time you are trying to convert then just use the normal php format to change the the format you want

PS. this will only work if you know the format of the date you want to convert

DarkseidNG
  • 92
  • 6
0

Simple format your date using DateTime class like below

1st : Create the date using createFromFormat with user given date format 'd-m-y'.

2nd : Format the date using format method

<?php

$dt = DateTime::createFromFormat('d-m-y', '01-01-17');
echo $dt->format('Y-m-d'); 

?>
JYoThI
  • 11,977
  • 1
  • 11
  • 26