Dates/Time
Data Types
Strings
function howManyTimesBetween(string $sentence): string { $errorMessage = 'Your question is strange'; $dates = array_map( fn($str) => DateTime::createFromFormat('Y-m-d', $str), explode(' and ', $sentence) ); $dates = array_filter($dates); if (count($dates) !== 2) { return $errorMessage; } $diffStrings = []; if ($dates[0] == $dates[1]) { return 'Dates are equals'; } $diff = $dates[0]->diff($dates[1]); $mapping = [ 'y' => 'year(s)', 'm' => 'month(s)', 'd' => 'day(s)', ]; foreach ($mapping as $p => $s) { if ($diff->$p) { $diffStrings[] = $diff->$p.' '.$s; } } return 'There are '.implode(', ', $diffStrings).' between '.$sentence; }
- function howManyTimesBetween(string $sentence): string
- {
- $errorMessage = 'Your question is strange';
$datesString = explode(' and ', $sentence);- $dates = array_map(
- fn($str) => DateTime::createFromFormat('Y-m-d', $str),
- 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]);- $dates = array_filter($dates);
if ($date1 === false or $date2 === false) {return $errorMessage;- if (count($dates) !== 2) {
- return $errorMessage;
- }
- $diffStrings = [];
if ($date1 == $date2) {- if ($dates[0] == $dates[1]) {
- 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)';- $diff = $dates[0]->diff($dates[1]);
- $mapping = [
- 'y' => 'year(s)',
- 'm' => 'month(s)',
- 'd' => 'day(s)',
- ];
- foreach ($mapping as $p => $s) {
- if ($diff->$p) {
- $diffStrings[] = $diff->$p.' '.$s;
- }
- }
if( ($diff->y && $diff->m) || $diff->m) return 'There are '.implode(', ', $diffStrings).' between '.$sentence;elseif($diff->d) return "There are ".$diff->d." day(s) between ".$sentence;- return 'There are '.implode(', ', $diffStrings).' between '.$sentence;
- }