User Tools

Site Tools


programmieren:php:date_functions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

programmieren:php:date_functions [2026/09/09 16:09] – created adminprogrammieren:php:date_functions [2026/10/05 12:01] (current) – [Usage] admin
Line 22: Line 22:
 The formats and how its parsed is very interesting. The formats and how its parsed is very interesting.
  
 +===== Usage =====
 +
 +I'll now show some scuffed but working usage of date functions. Its the logic for the Dashboards Birthday slide.
 +
 +<code php>
 +$employees = Employees::all();
 +
 +$birthdayToday = false;
 +$diffs = [];
 +foreach ($employees as $employee) {
 +    $separatedDate = explode('-', $employee->value);
 +
 +    $birthday = date_create($separatedDate[1] . '/' . $separatedDate[2]);
 +    $currentDay = date_create("today");
 +
 +    if ($birthday->format('Y-m-d') < $currentDay->format('Y-m-d')) {
 +        $birthday->add(date_interval_create_from_date_string("1 year"));
 +    }
 +
 +    $diff = date_diff($birthday, $currentDay);
 +    $diff = $diff->days;
 +
 +    $diffs += [$employee->name => $diff];
 +}
 +
 +asort($diffs, SORT_NUMERIC);
 +$birthdayPeople[] = array_key_first($diffs);
 +$birthdayDiff = $diffs[$birthdayPeople[0]];
 +
 +$multipleBirthday = array_keys($diffs, $birthdayDiff, true);
 +
 +if (array_count_values($multipleBirthday) >= 2) {
 +    $birthdayPeople = [];
 +    foreach ($multipleBirthday as $multipleBirthdayPerson) {
 +        $birthdayPeople[] = $multipleBirthdayPerson;
 +    }
 +}
 +
 +if ($birthdayDiff === 0) {
 +    $birthdayToday = true;
 +}
 +if ($birthdayDiff === 1) {
 +    $message = 'morgen.';
 +} else {
 +    $message = 'in ' . $birthdayDiff . ' Tagen.';
 +}
 +</code>
 +
 +The employee list is a list of Enums which contain the employees name and their birthdate as the value.
 +
 +We first foreach through each employee and separate the year from the rest of the date as it is not relevant for birthdays since birthdays are every year.
 +
 +We then create DateTime objects out of the birthday and the current day.
 +
 +Then if the birthday is in the past we move it to the next year since else the "diff" would also mention birthdays that have already passed.
 +
 +We then get the diff of the birthday and today and add it to an array with the employees name as the key.
 +
 +We then sort which birthday is the closest to the current day and add the person to the birthday people array. It is an array because multiple people can be born on the same day.
 +
 +We then check IF the most recent birthday has multiple people born on it. If so we add both to the array.
 +
 +We then check if the birthday is today as it influences what is displayed.
 +
 +We also check if the birthday is tomorrow since it influences the message.
programmieren/php/date_functions.txt · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki