Skip to content

Instantly share code, notes, and snippets.

@lomotech
Last active January 13, 2022 06:54
Show Gist options
  • Save lomotech/e044a610dfe33b638df28b9dbc4bb235 to your computer and use it in GitHub Desktop.
Save lomotech/e044a610dfe33b638df28b9dbc4bb235 to your computer and use it in GitHub Desktop.
Date range converter
<?php
namespace App\Libraries;
use Carbon\Carbon;
class DateRangeConverter
{
public static function humanReadable($startDate, $endDate)
{
$startDateTemp = explode('-', $startDate);
$endDateTemp = explode('-', $endDate);
$startDate = Carbon::parse($startDate);
$endDate = Carbon::parse($endDate);
//diff year
if ($startDateTemp[0] != $endDateTemp[0]) {
// 31-12-2021 - 01-01-2022
return $startDate->format('d M Y') . ' - ' . $endDate->format('d M Y');
}
//same year diff month
if ($startDateTemp[1] != $endDateTemp[1]) {
// 31-01 - 01-02-2022
return $startDate->format('d M') . ' - ' . $endDate->format('d M Y');
}
//diff day
if ($startDateTemp[2] != $endDateTemp[2]) {
// 30 - 31-02-2022
return $startDate->format('d') . ' - ' . $endDate->format('d M Y');
}
//same day
// 01-02-2022
return $endDate->format('d M Y');
}
public static function test()
{
$startDate = '31-12-2021';
$endDate = '01-01-2022';
echo 'test 1: ' . $startDate . ' - ' . $endDate . PHP_EOL;
echo self::humanReadable($startDate, $endDate).PHP_EOL;
$startDate = '01-01-2022';
$endDate = '01-02-2022';
echo 'test 2: ' . $startDate . ' - ' . $endDate . PHP_EOL;
echo self::humanReadable($startDate, $endDate).PHP_EOL;
$startDate = '01-01-2022';
$endDate = '31-01-2022';
echo 'test 3: ' . $startDate . ' - ' . $endDate . PHP_EOL;
echo self::humanReadable($startDate, $endDate).PHP_EOL;
$startDate = '01-01-2022';
$endDate = '01-01-2022';
echo 'test 4: ' . $startDate . ' - ' . $endDate . PHP_EOL;
echo self::humanReadable($startDate, $endDate).PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment