I'm using substr()
to get a date string from a long text, date found using the preg_match()
function.
I then use strtotime()
to convert this string to an epoch timestamp, because I need to do a comparison with another date already in this format.
It seems to work quite inconsistently, and after some testing, I can't seem to find the source of the bug. While the date string returned by substr()
is always correct, the strtotime()
function doesn't always work. Note that the substr()
is extracted from a larger string, itself coming from a database. Could the problem come from hidden character, or formatting ?
<?php
$DateString = substr($text, $matches[sizeof($matches) - 1][1] - 22, 17); //$DateString = the expected '2018-03-21 08:04' when echo
$DateString_hardcoded = '2018-03-21 08:04';
$DateEpoch = strtotime($DateString); //$DateEpoch is null
$DateEpoch_hardcoded = strtotime($DateString_hardcoded); //$DateEpoch_hardcoded return the expected 1521619440
?>
What I don't understand is that sometimes, the string date gets converted correctly, using the exact same code. For instance, when
substr($text, $matches[sizeof($matches) - 1][1] - 22, 17) = '2010-08-23 16:10', $DateEpoch = 1282579800
as expected.
Turns out I just don't know how to count, and I had to do -21 and not - 22 for the starting index for substr(). I ended up with a fine date, but with blank space at the very beginning. I don't know why it didn't show up when echo. Solved.