Skip to content

Instantly share code, notes, and snippets.

@kyleridolfo
Forked from paulofreitas/birthdays.php
Created February 7, 2017 02:18
Show Gist options
  • Save kyleridolfo/3cd253fddcb5ba1b8925cdb5eeadd8a9 to your computer and use it in GitHub Desktop.
Save kyleridolfo/3cd253fddcb5ba1b8925cdb5eeadd8a9 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