Ad
Date Time
Strings
  • Adjust output with sprintf formatting.
  • Made it more readable.
  • Create separate functions for array formatting and difference retrieve
Code
Diff
  • function howManyTimesBetween(string $sentence): string
    {
        if (!preg_match('/^(?<date1>\d{4}-\d{2}-\d{2}) and (?<date2>\d{4}-\d{2}-\d{2})$/', $sentence, $dates)) {
            return 'Your question is strange';
        }
    
        $dates      = array_map('date_create', $dates);
        $difference = getDiff($dates);
      
        if ( empty( $difference ) ) {
          return 'Dates are equals';
        }
    
        return sprintf(
          'There are %s between %s',
          implode(', ', getDiffStringArray( $difference ) ),
          $sentence
        );
    }
    
    function getDiff(array $dates) {
      $difference = $dates['date1']->diff($dates['date2']);
      
      if ( empty( $difference->days ) ) {
        return false;
      }
      
      return $difference;
    }
    
    function getDiffStringArray($difference): array {
      $formats     = ['%y year(s)', '%m month(s)', '%d day(s)'];
      $diffStrings = [];
    
      foreach( $formats as $format ) {
        $diffStrings[] = $difference->format($format);
      }
    
      return preg_grep('/^0/', $diffStrings, PREG_GREP_INVERT);
    }
    • function howManyTimesBetween(string $sentence): string
    • {
    • if (!preg_match('/^(?<date1>\d{4}-\d{2}-\d{2}) and (?<date2>\d{4}-\d{2}-\d{2})$/', $sentence, $dates)) {
    • return 'Your question is strange';
    • }
    • $dates = array_map('date_create', $dates);
    • if (!($diff = $dates['date1']->diff($dates['date2']))->days) {
    • $dates = array_map('date_create', $dates);
    • $difference = getDiff($dates);
    • if ( empty( $difference ) ) {
    • return 'Dates are equals';
    • }
    • $diffStrings = [$diff->format('%y year(s)'), $diff->format('%m month(s)'), $diff->format('%d day(s)')];
    • $diffStrings = preg_grep('/^0/', $diffStrings, PREG_GREP_INVERT);
    • return sprintf(
    • 'There are %s between %s',
    • implode(', ', getDiffStringArray( $difference ) ),
    • $sentence
    • );
    • }
    • function getDiff(array $dates) {
    • $difference = $dates['date1']->diff($dates['date2']);
    • if ( empty( $difference->days ) ) {
    • return false;
    • }
    • return 'There are '.implode(', ', $diffStrings)." between $sentence";
    • return $difference;
    • }
    • function getDiffStringArray($difference): array {
    • $formats = ['%y year(s)', '%m month(s)', '%d day(s)'];
    • $diffStrings = [];
    • foreach( $formats as $format ) {
    • $diffStrings[] = $difference->format($format);
    • }
    • return preg_grep('/^0/', $diffStrings, PREG_GREP_INVERT);
    • }