Skip to content

Instantly share code, notes, and snippets.

@paulofreitas
Created February 20, 2016 02:42
Show Gist options
  • Save paulofreitas/04740d6d123c5a5dd776 to your computer and use it in GitHub Desktop.
Save paulofreitas/04740d6d123c5a5dd776 to your computer and use it in GitHub Desktop.
Working with birthdays using Carbon
<?php
/*
* HOW TO TEST:
* composer require illuminate/support nestbot/carbon fzaninotto/faker
*/
require 'vendor/autoload.php';
date_default_timezone_set('America/Sao_Paulo');
header('Content-Type: text/plain');
use Carbon\Carbon;
$is_birthday = function ($person) {
return $person['birthday']->isBirthday();
};
$persons = collect(range(1, rand(1, 1000)))->map(function () {
$random = Faker\Factory::create();
return [
'name' => $random->name,
'birthday' => Carbon::parse($random->date),
];
});
$birthdays = $persons->filter($is_birthday);
$next_birthdays = $persons->reject($is_birthday)
->map(function ($person) {
$person['birthday'] = $person['birthday']->copy()->year(Carbon::now()->year);
if ($person['birthday']->isPast()) {
$person['birthday'] = $person['birthday']->copy()->addYear();
}
return $person;
})
->sortBy(function ($person) {
return $person['birthday']->format('Y-m-d');
});
if ($birthdays->count()) {
print "Birthdays:\n\n";
foreach ($birthdays as $person) {
printf("%s => %s\n", $person['name'], $person['birthday']->age);
}
print "\n";
} else {
print "No one is celebrating a birthday today. :/\n\n";
}
if ($next_birthdays->count()) {
print "Next birthdays:\n\n";
foreach ($next_birthdays as $person) {
printf(
"%s => %s (%s)\n",
$person['name'],
$person['birthday']->format('M d, Y'),
$person['birthday']->diffForHumans()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment