0

I have an excel file. Date column is like this 29/01/21 that means dd/mm/yy.

I read file

$date2 = strtotime($row[1]);
            $date = date('d-m-Y',$date2);

Its result 000000000.

When I changed Y-m-d instead of d-m-Y. Its read but when date or mount greater than 12 its result is NULL.

How can I read this data correctly?

xxx
  • 7
  • 1
  • `strtotime` doesn't recognise dd/mm/yy format. Use https://www.php.net/manual/en/datetime.createfromformat.php instead. – ADyson Sep 30 '21 at 08:20
  • 1
    Please read this for more details: [How to parse a date string in PHP?](https://stackoverflow.com/questions/2767324/how-to-parse-a-date-string-in-php) – ADyson Sep 30 '21 at 08:22

1 Answers1

1

Ok so here is a fix. strtotime can't read your dd/mm/yy format automatically. You have to re-order the date and add the century onto the year to make it yyyy/mm/dd:

$date2 = "29/01/21";
$d = explode("/",$date2);
$newDate2 = "20" . $d[2] . "/" . $d[1] . "/" . $d[0];
//echo $newDate2 . "\n";
$newDate = date('d/m/Y', strtotime($newDate2));
echo $newDate;
ADyson
  • 57,178
  • 14
  • 51
  • 63
Shlomtzion
  • 674
  • 5
  • 12
  • OP is getting the date from the Excel sheet as `29/01/21`, not `01-02-2021`. It makes a difference. – ADyson Sep 30 '21 at 08:21
  • Thanks for your edit but it's irrelevant. OP is getting the _input_ in dd/mm/yy format. Nothing to do with the output. – ADyson Sep 30 '21 at 08:23
  • I see, we need to explode it and reorder it ... – Shlomtzion Sep 30 '21 at 08:25
  • 1
    No we just need to use DateTime::createFromFormat - much less fiddly and less error-prone. No need to re-invent the wheel. https://www.php.net/manual/en/datetime.createfromformat.php, https://stackoverflow.com/questions/2767324/how-to-parse-a-date-string-in-php – ADyson Sep 30 '21 at 08:25
  • 1
    Anyway, re-ordering it still wouldn't work, because the year is in two-digit format, so strtotime still can't parse it correctly. Demo: http://sandbox.onlinephpfunctions.com/code/cbf21b656ebaf2bda60a8db36bda5171072c8717 P.S. https://www.php.net/manual/en/datetime.formats.date.php explains the date formats which strtotime and other related functions can understand automatically. – ADyson Sep 30 '21 at 08:27
  • 1
    You _could_ of course add the `20` to the start, but who knows if it was really supposed to be `19` or `21`...but then that's a problem the OP will face regardless, so I think that's acceptable. – ADyson Sep 30 '21 at 08:29
  • I edited your answer to make it clearer and remove the incorrect stuff :-) – ADyson Sep 30 '21 at 08:29
  • I have revised my answer with code to show how to overcome the issue. – Shlomtzion Sep 30 '21 at 08:30
  • 1
    @ADyson - thanks! was about to do it...:) – Shlomtzion Sep 30 '21 at 08:30