phpinspectionsea icon indicating copy to clipboard operation
phpinspectionsea copied to clipboard

Add Inspection to check for correct date format

Open cebe opened this issue 4 years ago • 2 comments
trafficstars

Description (screenshot):

We recently discovered a very subtile error in our code that generates files for exchange with external systems. When generating files with a timestamp in the name, it often uses code like this:

$dateTime = (new \DateTime())->format('Ymdhis');

It is not obvious from the code above that this should be YmdHis instead, which is 24h format instead of 12h format.

In our case this resulted in duplicate file names and wrong ordering which was very hard to figure out.

An inspection could suggest to use 24h format instead.

cebe avatar Sep 16 '21 14:09 cebe

Interesting, is there a reference to the codebase? It sounds like context-dependent and we need check if we could detect the context properly.

ea-inspections-team avatar Dec 04 '21 09:12 ea-inspections-team

Hard to say how to figure it out from the context. In my case it looked like this (used in a filename):

        $dateTime = (new \DateTime())->format('YmdHis');
        $exportFilename = $this->csvFilePrefix . '_' . $dateTime . '.csv';
        $exportFile = Yii::getAlias(rtrim($this->csvExportPath, '/') . '/' . $exportFilename);
        $this->writeCsvFile($exportFile, $lines);

Which does not really add anything, but a slightly different rule could be figured by checking for this:

If we have a use of date() or DateTime::format(), which uses h or g (12hour format) but does not include a or A, for am/pm, it could add a hint like "h/g without am/pm indicator is not a unique time description, you might want to use H/G or add a/A for am/pm."

Only apply this on formats that have more than one entry, e.g. it should not trigger on date('h') but it should trigger on date("h:i:s").

For reference: https://www.php.net/manual/de/datetime.format.php

cebe avatar Apr 21 '22 15:04 cebe