katie hudson
katie hudson

Reputation: 2893

strtotime() is treating my d/m/Y date like m/d/Y

I asked a question earlier but realised I was asking the wrong thing. I have an array which takes the following format

Array
(
    [0] => Array
        (
            [ID] => 10000
            [Date] => 21/11/2013
            [Total] => 10
        )
    ...
)

So it has an ID, Date and Total. One issue is, I do not know what format the Date column might be, but whatever format it is I need to convert it into the format dmy.

So I am looping my array, I know that the key will always be Date.

foreach($this->csvData as $item) {
    foreach($item as $key => $value) {
        if($key === 'Date') {
            $item[$key][$value] = date("dmy", strtotime($value));
        }
    }
}

I am experiencing a couple of issues with the above. Firstly, after the looping, if I output $this->csvData, the date values have not been converted to the new values. I know I am in the right place because if I do this inside the if

print_r(date("dmy", strtotime($value));

I can see the altered dates. I dont think I am reassigning them correctly though?

The other thing I am attempting to do is this. If the date is completely wrong, say some random thing like 23455, then I want to remove the whole element from the array.

Is this possible? I know about validating dates, but it always seems to be validating against one particular format, whereas I do not know what the format will be.

Upvotes: 0

Views: 858

Answers (1)

dWinder
dWinder

Reputation: 11642

Your problem lay in dd/mm/yyyy format.

From strtotime documentation:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

So "21/11/2013" fail as there is no month 21...

Use - as "21-11-2013"

If you don't know the format you can check the return value of strtotime before:

$arr = [["id" => 100, "data" => "21-11-2013"]];

foreach($arr as $k => &$e) {
    $val = strtotime($e["data"]) ? strtotime($e["data"]) : strtotime(str_replace("/", "-", $e["data"]));
    $e["data"] = date("m/d/y", $val);
    if (!$val) unset($arr[$k]); // if non valid date remove from array
}

Live example: 3v4l

Upvotes: 3

Related Questions