0

My input date format is dd/mm/yy. I am using the following code to convert it into yyyy-mm-dd.

    $cal_date= $fileop[1];
    $date = str_replace('/', '-', $cal_date);
    $invdate=date('Y-m-d',strtotime($date));

Result i got is 24/10/13-->2024-10-13. Can anyone correct me.

Here two conversions 2digit year to 4 digit year and /replaced by -dash

Indra
  • 390
  • 1
  • 3
  • 12
  • `strtotime()` has a [strict list of formats](http://www.php.net/manual/en/datetime.formats.date.php) that it will understand, and `dd-mm-y` or `dd/mm/y` are not part of that list. – Sammitch Oct 25 '13 at 16:55

4 Answers4

3

Using the DateTime object might be better

try{
   $date = DateTime::createFromFormat('d/m/y',$cal_date);
   $invdate = $date->format('Y-m-d');
} catch (Exception $e) {
   echo $e->getMessage(); // or
   print_r(DateTime::getLastErrors());
}
aynber
  • 22,380
  • 8
  • 50
  • 63
0
$date = DateTime::createFromFormat('d/m/y',$cal_date);
$break = explode("/", $date);
$yearComp = $break[2];
if($yearComp < 70)
    $invdate = $date->format('Y-m-d'); 
else {
    // code that would add 100 years to the date generated }

But just know that 69 would print out 2069 but 70 would be 1970. If you won't get to 70, then this should be fine

Yanki Twizzy
  • 7,771
  • 8
  • 41
  • 68
-1

Another way - See The Demo Here

<?php

$date= "02/05/2013"; //dd/mm/yy
$dd=substr($date, 0, 2);
$mm=substr($date, 3, 2);
$yy=substr($date, 6, 4);

echo $yy."/".$mm."/".$dd; // yyyy-mm-dd.

?>
underscore
  • 6,495
  • 6
  • 39
  • 78
-1

In one shoot:

$invdate = date_format(date_create_from_format('m/d/y', $fileop[1]), 'Y-m-d');

If you are not confident with the imput date format:

if ($invdate = date_create_from_format('m/d/y', $fileop[1])) {
    $invdate = date_format($invdate, 'Y-m-d'); //date format yyyy-mm-dd
} else {
    echo "ERROR: '{$fileop[1]}' has not the date format mm/dd/yy";
}
evalarezo
  • 1,134
  • 7
  • 13
  • Excellent. It works but returns an error "date_format() expects parameter 1 to be DateTimeInterface, boolean given in" – Indra Oct 25 '13 at 17:26
  • That is because you are using a different date format than the expected. Consider fix your question example, so it must use the same date format specified at the question title. – evalarezo Dec 01 '13 at 12:14