i am trying to get holidays from an array. the code outputs :
Neujahr: So., 1. Januar 2022 01:0101
Allerheiligen: Mi., 1. November 2023 01:0101
but should output:
Neujahr: So., 1. Januar 2023 01:0101 (2023 not 2022 !! )
This only happens with date 01-01. every other date is displayed correctly.
What is the reason for this and how can this be solved?
$formatter = new IntlDateFormatter(
'de_DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'Europe/Berlin',
IntlDateFormatter::GREGORIAN,
'EEE, d. MMMM Y'
);
$date = date('m/d/Y h:i:s ', time());
$dateFormat = 'EEE, d MMMM Y';
$timeFormat = 'H:mm';
$holidays = [
'01-01' => 'Neujahr',
'11-01' => 'Allerheiligen'
];
foreach ($holidays as $date => $holiday) {
$datetime = DateTime::createFromFormat('m-d-Y', $date . '-' . date('Y'));
$formatted_date = $formatter->format($datetime);
$formatted_time = date($timeFormat, strtotime($date));
echo $holiday . ': ' . $formatted_date . ' ' . $formatted_time . '<br>';
}
Use a lowercase "y" for the year in the formatting string. Using the uppercase "Y" means "week of year" which, since the first holiday is the first day of January, ends up being 2022. For dates close to the beginning or end of the year, that formatting pattern often ends up being the previous or next year. The lowercase "y" gives you the year of the date provided which is what you are looking for.
$formatter = new IntlDateFormatter(
'de_DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'Europe/Berlin',
IntlDateFormatter::GREGORIAN,
'EEE, d. MMMM y'
);