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?

2

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

9 Comments

OP is getting the date from the Excel sheet as 29/01/21, not 01-02-2021. It makes a difference.
No we just need to use DateTime::createFromFormat - much less fiddly and less error-prone. No need to re-invent the wheel. php.net/manual/en/datetime.createfromformat.php, stackoverflow.com/questions/2767324/…
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: sandbox.onlinephpfunctions.com/code/… P.S. php.net/manual/en/datetime.formats.date.php explains the date formats which strtotime and other related functions can understand automatically.
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 - thanks! was about to do it...:)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.