15

'17:15' < '09:45' === false
'5:15pm' < '9:45am' === true

I either need a language with a stronger type system, or coworkers who understand that comparing raw time input in validation is a bad idea 😡

Comments
  • 0
    😱😱
  • 1
    Needs more regex.
  • 0
    This is the reason why PHP is called shit. Because of these goddamn script kiddies who dont know what they are doing... what's so hard about comparing hours and minutes AS INTEGERS...
  • 2
    @jamiek94 Rather not as integers, because it doesn't solve the am/pm problem. Parsing the time as soon as it enters the application, and comparing them using tested time objects is the way to go.

    I do think it's not really PHP's fault, languages with much more advanced type systems still consider lists to be orderable if their parts are, and tend to declare comparison operators as polymorphic generics (instance (Ord a) => Ord [a] for strings where a is char).

    In this case it was just 100% developer error, the method should have been isolated and should have only accepted DateTime or Carbon objects.
  • 1
    Check out the carbon library, really useful for dates/times
  • 1
    @lainga9 Yup, we already use it, it takes most of the pain away.

    But in this case a function which validates start and ends times got passed a parameter without typehint.

    Comparing H:i formatted strings works, because the order of the chars is always smaller for earlier times.

    This is why I tend to force devs to use full typehints in PHP:

    function validate(Carbon $start, Carbon $end): bool { // etc

    That way it will complain if you pass a string, unix timestamp, or DateTime object, and you know it can only return true or false instead of truthy/falsy values.

    Makes it much easier to debug, as it will instantly fail instead of succeed 95% of the time.
Add Comment