Ad
Dates/Time
Data Types
Strings

You must display literally the difference between two dates textual

Exemple input howManyTimesBetween("1995-12-02 and 2010-01-05")
Will return "There are 14 year(s), 10 month(s), 8 day(s) between 1995-12-02 and 2010-01-05"

Constraints and permissions

If constraints are not respected, the function should return "Your question is strange"

  • The two dates can be inverted (the oldest can be at start or end), and will give the same gap between the twice dates
  • If there are no months/day/years gap. Don't display it in the sentence (exemple : howManyTimesBetween("2010-01-05 and 2010-01-10") will return "There are 5 day(s) between 1995-12-02 and 2010-01-05")
  • If the two date are the same, will return "Dates are equals"
  • The date format is Y-m-d (conforming to https://www.php.net/manual/fr/datetime.format.php). There is not hours or others
  • The sentence should always do "{date} and {date}"
  • The end of the response sentence will is the same than the input whatever the order of dates
function howManyTimesBetween(string $sentence): string
{
    $errorMessage = 'Your question is strange';
  
    $datesString = explode(' and ', $sentence);
  
    if (count($datesString) !== 2) {
      return $errorMessage;
    }
  
    $date1 = DateTime::createFromFormat('Y-m-d', $datesString[0]);
    $date2 = DateTime::createFromFormat('Y-m-d', $datesString[1]);
  
    if ($date1 === false or $date2 === false) {
        return $errorMessage;
    }
  
    $diffStrings = [];
  
    if ($date1 == $date2) {
        return 'Dates are equals';
    }
  
    $diff = $date1->diff($date2);
    
    if ($diff->y) {
        $diffStrings[] = $diff->y.' year(s)';
    }
    
    if ($diff->m) {
        $diffStrings[] = $diff->m.' month(s)';
    }
    
    if ($diff->d) {
        $diffStrings[] = $diff->d.' day(s)';
    }
  
    return 'There are '.implode(', ', $diffStrings).' between '.$sentence;
}